package com.qianclass.talklive.app.activity;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.util.Base64;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewParent;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.ConsoleMessage;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.ImageInfo;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.BitmapCallback;
import com.orhanobut.logger.Logger;
import com.qianclass.talklive.R;
import com.qianclass.talklive.app.InterfaceBack.OnDragFrameLayoutClickListener;
import com.qianclass.talklive.app.InterfaceBack.OnDrawTouchListener;
import com.qianclass.talklive.app.InterfaceBack.OnLikeListener;
import com.qianclass.talklive.app.InterfaceBack.OnWebClickListener;
import com.qianclass.talklive.app.adapter.CatalogListAdapter;
import com.qianclass.talklive.app.adapter.ChatHistoryAdapter;
import com.qianclass.talklive.app.adapter.EmojiAdapter;
import com.qianclass.talklive.app.adapter.OperationMenuAdapter;
import com.qianclass.talklive.app.adapter.SortMemberAdapter;
import com.qianclass.talklive.app.bean.AddGraffitiBean;
import com.qianclass.talklive.app.bean.AuthOpenFile;
import com.qianclass.talklive.app.bean.CatalogBean;
import com.qianclass.talklive.app.bean.ClockBean;
import com.qianclass.talklive.app.bean.CommandInfoBean;
import com.qianclass.talklive.app.bean.DzBean;
import com.qianclass.talklive.app.bean.FileInfo;
import com.qianclass.talklive.app.bean.GraffitiInfo;
import com.qianclass.talklive.app.bean.GraffitiOrdermsgBean;
import com.qianclass.talklive.app.bean.GraffitiPaintmsgBean;
import com.qianclass.talklive.app.bean.GraffitiPathPage;
import com.qianclass.talklive.app.bean.GraffitiShapeBean;
import com.qianclass.talklive.app.bean.HistoryChatMsgBean;
import com.qianclass.talklive.app.bean.IMHistoryInfoBean;
import com.qianclass.talklive.app.bean.LockBean;
import com.qianclass.talklive.app.bean.MemberItemInfo;
import com.qianclass.talklive.app.bean.MicCameraBean;
import com.qianclass.talklive.app.bean.MusicOrderBean;
import com.qianclass.talklive.app.bean.ObjData;
import com.qianclass.talklive.app.bean.OpenWebCommandBean;
import com.qianclass.talklive.app.bean.OperationMenuBean;
import com.qianclass.talklive.app.bean.PositionXYBean;
import com.qianclass.talklive.app.bean.ReconnectIMBean;
import com.qianclass.talklive.app.bean.RemarksInfoBean;
import com.qianclass.talklive.app.bean.ShareScreenBean;
import com.qianclass.talklive.app.bean.SortMemberBean;
import com.qianclass.talklive.app.bean.TextWhiteBoardBean;
import com.qianclass.talklive.app.bean.VideoBody;
import com.qianclass.talklive.app.bean.WebMediaBean;
import com.qianclass.talklive.app.bean.WebTurnCommandBean;
import com.qianclass.talklive.app.bean.WhiteBoardBean;
import com.qianclass.talklive.app.bean.WhiteBoardBody;
import com.qianclass.talklive.app.fragment.VideoTextureFragment;
import com.qianclass.talklive.app.im.ConstantDefination;
import com.qianclass.talklive.app.im.IMEgine;
import com.qianclass.talklive.app.im.IMInstance;
import com.qianclass.talklive.app.json.ImSendMessge.SendClearGraffitoMessage;
import com.qianclass.talklive.app.json.ImSendMessge.SendClockMessage;
import com.qianclass.talklive.app.json.ImSendMessge.SendControlCommandMessage;
import com.qianclass.talklive.app.json.ImSendMessge.SendLockMessage;
import com.qianclass.talklive.app.json.ImSendMessge.SendMicVideoMessage;
import com.qianclass.talklive.app.json.ImSendMessge.SendMusicCommandMessage;
import com.qianclass.talklive.app.json.ImSendMessge.SendOpenFileMessge;
import com.qianclass.talklive.app.json.ImSendMessge.SendPageturnMessge;
import com.qianclass.talklive.app.json.ImSendMessge.SendRaiseHandMessge;
import com.qianclass.talklive.app.json.ImSendMessge.SendSpeakControlMessage;
import com.qianclass.talklive.app.json.upLoadPhotoService;
import com.qianclass.talklive.app.screenshots.FileUtils;
import com.qianclass.talklive.app.screenshots.ScreenShot;
import com.qianclass.talklive.app.utils.CharacterParser;
import com.qianclass.talklive.app.utils.ColorUtils;
import com.qianclass.talklive.app.utils.CompressPhotoUtils;
import com.qianclass.talklive.app.utils.Constant;
import com.qianclass.talklive.app.utils.DensityUtil;
import com.qianclass.talklive.app.utils.DownLoadMusic;
import com.qianclass.talklive.app.utils.FileLogUtils;
import com.qianclass.talklive.app.utils.Info;
import com.qianclass.talklive.app.utils.LogUtil;
import com.qianclass.talklive.app.utils.PinyinComparator;
import com.qianclass.talklive.app.utils.SharedPreferencesUtils;
import com.qianclass.talklive.app.utils.SortUtils;
import com.qianclass.talklive.app.utils.StringEncrypt;
import com.qianclass.talklive.app.utils.ThreadUtils;
import com.qianclass.talklive.app.utils.ToastUtils;
import com.qianclass.talklive.app.utils.UpPhotoProgressDialog;
import com.qianclass.talklive.app.utils.VerificationKeyUtils;
import com.qianclass.talklive.app.view.DragFrameLayout;
import com.qianclass.talklive.app.view.DrawableWebView;
import com.qianclass.talklive.app.view.Graffiti.GraffitiParams;
import com.qianclass.talklive.app.view.Graffiti.GraffitiView;
import com.qianclass.talklive.app.view.ShaderProgressBar;
import com.qianclass.talklive.app.view.TimerView;
import com.qianclass.talklive.app.view.meunView.PromotedActionsLibrary;
import com.qianclass.talklive.app.view.sort.ClearEditText;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.agora.rtc.Constants;
import io.agora.rtc.IRtcEngineEventHandler;
import io.agora.rtc.RtcEngine;
import io.agora.rtc.RtcEngineEx;
import io.agora.rtc.video.VideoCanvas;
import okhttp3.Call;
import okhttp3.Response;

public class VideoActivity extends BaseEngineEventHandlerActivity
        implements OnClickListener, IVideoActivity, OnPreparedListener, OnBufferingUpdateListener,
                   OnLikeListener
{
    public static final int CHANNEL_PROFILE_COMMUNICATION = 0;//默认
    public static final int CHANNEL_PROFILE_LIVE_BROADCASTING = 1;
    public static final int CLIENT_ROLE_AUDIENCE              = 2;

    private static final String TAG               = "VideoActivity";
    private static final int    GOOUT             = 171;
    private static final int    LIMITTALK         = 172;
    private static final int    ALLOWTALK         = 173;
    private static final int    ISLIMITTALK       = 174;
    private static final int    RECORD_AUDIO      = 1700;
    private static final int    GETCHANNELKEYSUC  = 1701;
    private static final int    SHARESCREEN_OPEN  = 1702;
    private static final int    SHARESCREEN_CLOSE = 1703;
    private static final int    GETRECORDKEYSUC  = 1704;
    private Context      mContext;
    private RtcEngineEx rtcEngine;
    private FrameLayout ll_whiteboard;
    public              int    mRemoteUserViewWidth = 0;
    public  LinearLayout ll_divide;
    public LinearLayout ll_below_video, mLlView;
    public TextView     tv_name;
    private String      str;
    public  FrameLayout frameLayout;
    public  int                 mRemoteUserViewH;
    private String              token;
    public int likenum, lnum;
    private String mUserName;
    /**
     * 聊天内容对象
     **/
    private JSONObject jsonObject;
    /**
     * 画点的集合
     **/
    private EditText mEtBody;
    public static IMEgine   egine;
    public        ImageView top, mIvEmoji;
    public Button mBtnSend;
    public  Bitmap     bitmap;
    private JSONObject msgjson, wbjson;
    public  float x, y;
    public ObjData xyPaint, xyPaint1;
    public int    p;
    public String mUrl1, mUrl4;
    private ImageView mArrowRight, mArrowLeft;
    private String imageurl;
    private TextView       mPageText;

    public int    color;
    public int    currentPage = 1;
    public int    mPageNums = 1;

    public String mp3Url;

    public final String fileDirWhiteBorad = Constant.WHITEBOARDFILEDIR;
    public        WhiteBoardBean          mWhiteBoardBean;
    public static String                  mGroup;
    public        Gson                    mGson;
    public BitmapUtils bitmapUtils;
    public        String      encode_eclass_json;
    public String      fileDir;
    public  ArrayList<String> item;
    private boolean member_pressed = false;
    private DzBean               mDzBean;
    private MicCameraBean        micCameraBean;
    private List<MemberItemInfo> userlist;

    private String channelkey;
    private JSONObject jsonrespose;
    private int        uuid, luuid;
    private JSONObject bigmsgjson, bigdata;
    private String bigwbdata, doc_server, doc_pagenum, doc_fileid;
    private String       wbdata;
    private JSONObject   js;
    private LinearLayout dm_layout;
    private LinearLayout all_view;
    private String       roomName;
    private long timeusedinsec;
    private boolean isstop = false;
    private String         docUrl;
    private List<String>   mp3list;
    private List<FileInfo> FileInfo_list;
    private List<FileInfo> bookInfoList;

    private Uri               uri;
    private int               mUserID, mUserType, mHostID, mRoomType, mRoomID;
    private String mUserAcount = "";
    private JSONObject courseinfojson;
    private String     subType;
    private String       pageturn_fileid;
    private AudioManager am;
    private TextWhiteBoardBean       textWhiteBoardBean;
    private String                   sub;
    private String                   infoStr;
    private Map<String, MediaPlayer> map;
    private Boolean isLimitTalk = false;
    // 计时器
    private TimerView mTimerView;
    // 计时器控件高度
    private int mTimerLayoutHeight ;
    // 计时器是否显示
    private boolean isTimerShow = true;
    // 计时器进出动画
    private boolean isAnimatorPlay = false;
    // 举手图标
    private ImageView mImageRaiseHand;
    // 学生端和老师端教材是不同页
    private              boolean                       differentPage        = false;
    // 手动翻页
    private              boolean                       mTurnPage            = false;
    // 记录页面轨迹集合
    private              Map<String, GraffitiPathPage> mGraffitiPathPageMap = new HashMap<>();
    private List<GraffitiPaintmsgBean> mGraffitiPaintData = new ArrayList<>();
    private static final int                           NETWORKTYPE_WIFI     = 0;
    private static final int                           NETWORKTYPE_MOBILE   = 1;
    private static final int                           NETWORKTYPE_NONE     = 3;
    private static final int REQUEST_CODE_PERMISSION_OTHER = 210;
    private static final int REQUEST_CODE_SETTING          = 300;
    private String            strAccount;
    private String            hostAccount;
    private int mScreenWidth;
    private int mScreenHeight;
    private List<Map<String, Object>> mEmojiData;

    private Handler mClockHandler = new Handler() {
        /*
         * edit by yuanjingchao 2014-08-04 19:10
         */
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);

            switch (msg.what) {
                case 1:
                    // 添加更新ui的代码
                    if (!isstop) {

                        updateView();
                        mClockHandler.sendEmptyMessageDelayed(1, 1000);
                    }
                    break;
                case GETCHANNELKEYSUC:

                    setupChannel();

                    LogUtil.i(TAG, "onCreate: -----" + mUserID + "----" + mUserName + "--" + mUserType);

                    break;
                case GETRECORDKEYSUC:

                    mRecordKey = (String) msg.obj;

                    LogUtil.e("mRecordkey", mRecordKey);
                    int result = rtcEngine.startRecordingService(mRecordKey);
                    if (result < 0) {
                        LogUtil.e("mRecordkey", "Failed to record");
                        mClockHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                getChannelKey(mRoomID + "", mUserID + "", "RECORDKEY");
                            }
                        }, 5 * 1000);
                    } else if (result == 0) {
                        LogUtil.e("mRecordkey", "Success to record");
                    }

                    startRecording();

                    break;
                case GOOUT:

                    AlertDialog alertDialog = new AlertDialog.Builder(VideoActivity.this).setTitle(getResources().getString(R.string.course_tip))
                            .setMessage(getResources().getString(R.string.course_detail_live_receive_goout))
                            .setIcon(android.R.drawable.ic_dialog_info)
                            .setPositiveButton(getResources().getString(R.string.course_sure), new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // 点击“确认”后的操作
                                    ThreadUtils.runOnSubThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (egine != null) {
                                                egine.UnRegister();
                                            }
                                        }
                                    });
                                    rtcEngine.leaveChannel();
                                    egine = null;
                                    musicRelease();
                                    if(isVoucherJump) {
                                        //rtcEngine.destroy();
                                        System.exit(0);
                                    }
                                    VideoActivity.this.finish();
                                }
                            }).show();
                    alertDialog.setCanceledOnTouchOutside(false);
                    alertDialog.setCancelable(false);
                    alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                        @Override
                        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                            if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0)
                            {
                                return true;
                            }

                            return false;
                        }
                    });

                    break;

                case LIMITTALK:
                    isLimitTalk = true;
                    Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_live_receive_limit_talk), Toast.LENGTH_SHORT).show();
                    break;
                case ALLOWTALK:
                    isLimitTalk = false;
                    Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_live_receive_allow_talk), Toast.LENGTH_SHORT).show();
                    break;
                case ISLIMITTALK:
                    Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_live_limit_send_msg), Toast.LENGTH_SHORT).show();
                    break;
            }
        }

    };
    private PopupWindow mPopupWindow;
    private AlertDialog mInputPageDialog;
    private VideoTextureFragment mVideoTextureFragment;
    private SwipeRefreshLayout mSwipeRefreshChat;
    private ListView mLvChatMember;
    private ListView mLvMember;
    private ChatHistoryAdapter mChatHistoryAdapter;
    private ArrayList<VideoBody> mChatMsgLists;
    private boolean mNoMoreChatHistory;
    private TextView mTvLoadHistoryChat;
    private ProgressBar mPbLoadHistoryChat;
    private int mHistoryChatPage;
    private boolean isAccountLocked;
    private boolean isVideoMode = true;
    private boolean isFrontCamera = true;
    private ImageView mIvCommonWord;
    private Button mBtnWbRefresh;
    private Button mBtnWbRemarks;
    private FrameLayout mFlRemarks;
    private TextView mTvRemarksContent;
    private long mRemoteClickLastTime;
    private boolean isRemarksShow;
    private String mRoomRemarks;
    private boolean isTimeStart;
    private boolean differentPageText;
    private TextView mTvMemberNumber;
    private int mMemberNumber;
    private boolean isIMReconnect;
    private int mVideoProfileType = -1;
    private TextView mTvNameIndicator;
    private DrawableWebView mWebView;
    private boolean isWebMode;
    private int mCurrentaction;
    private List<FileInfo> mH5List;
    private boolean isWebLoaded;
    private boolean isZipTextBook;
    private boolean isWebReload;
    private int mWebViewWidth;
    private int mWebViewHeight;
    private long mLastWebClickTime;

    /*开启录像*/
    private void startRecording() {
        new Thread(new Runnable() {
            public void run() {
                VerificationKeyUtils keyUtils = new VerificationKeyUtils();
                String VerificationKey = keyUtils.getVerificationKey(TalkApplication.getMechanismId());

                HttpUtils httpUtils = new HttpUtils();
                RequestParams params = new RequestParams();
                params.addBodyParameter("Version", Info.APIVERSION);
                params.addBodyParameter("UA", "Android");
                params.addBodyParameter("RoomID", mRoomID + "");
                params.addBodyParameter("UserID", mUserID + "");
                params.addBodyParameter("VerificationKey", VerificationKey);

                String url = Constant.getStartRecording();

                FileLogUtils.write("StartRecording:" + url);

                httpUtils.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {

                    public void onFailure(HttpException a, String respose) {
                        LogUtil.i(TAG, "开启失败");
                    }

                    public void onSuccess(ResponseInfo<String> respose) {
                        LogUtil.i(TAG, "startRecording onSuccess: " + respose.result);
                        try {
                            JSONObject jsonObject = new JSONObject(respose.result);
                            boolean result = jsonObject.getBoolean("Result");

                            if (!result) {
                                LogUtil.e("startRecoding", jsonObject.getString("code"));
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }).start();
    }

    /*停止录像*/
    private void stopRecording() {
        new Thread(new Runnable() {
            public void run() {
                VerificationKeyUtils keyUtils = new VerificationKeyUtils();
                String VerificationKey = keyUtils.getVerificationKey(TalkApplication.getMechanismId());

                HttpUtils httpUtils = new HttpUtils();
                RequestParams params = new RequestParams();
                params.addBodyParameter("Version", Info.APIVERSION);
                params.addBodyParameter("UA", "Android");
                params.addBodyParameter("RoomID", mRoomID + "");
                params.addBodyParameter("UserID", mUserID + "");
                params.addBodyParameter("VerificationKey", VerificationKey);

                String url = Constant.getStopRecording();

                FileLogUtils.write("stopRecording:" + url);

                httpUtils.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {

                    public void onFailure(HttpException a, String respose) {
                        LogUtil.i(TAG, "onFailure: 停止录像失败");
                    }

                    public void onSuccess(ResponseInfo<String> respose) {
                        LogUtil.i(TAG, "stoprecording onSuccess: " + respose.result);
                        try {
                            JSONObject jsonObject = new JSONObject(respose.result);
                            boolean result = jsonObject.getBoolean("Result");

                            if (!result) {
                                LogUtil.e("stopRecoding", jsonObject.getString("code"));
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }).start();
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient mClient;
    private FrameLayout                 mFlVideoContainer;
    private LinearLayout                mLlLocalVideoContainer;
    private FrameLayout                 mFlLocalVideoViewContainer;
    private LinearLayout                mLlRemoteVideoContainer;
    private FrameLayout                 mFlRemoteVideoViewContainer;
    private boolean                     mVideofullscreenflag;
    private int                         mRemoteStreamUid;
    private ProgressBar                 mProgressBar;
    /**
     * mRoomType=3时，用户的角色是否是主播
     */
    private boolean                     mAnchor;
    private CharacterParser             mCharacterParser;
    private PinyinComparator            mPinyinComparator;
    private SortMemberAdapter           mSortMemberAdapter;
    private ClearEditText               mClearEditText;
    private List<SortMemberBean>        mSourceDateList;
    private AlertDialog                 mQuickAnswersDialog;
    private VolumeChangeVolumeReceiver  mVolumeReceiver;
    private boolean                     mSpeakerPhoneOn;
    private WifiChangeBroadcastReceiver mWifiChangeBroadcastReceiver;
    private long                        mShowWifiMsgTime;
    private DownLoadMusic               mDownLoadMusic;
    private boolean                     localMainViewFlag;
    private SimpleDraweeView mFrescoGif;
    private RelativeLayout mRlDialogue;
    private RelativeLayout mRlMember;
    private View mViewDialogue;
    private View mViewMember;
    private ImageView mIvMessage;
    private int mFileID;
    private boolean isVoucherJump;
    private String mFileName;
    private List<CatalogBean> mCatalogLists;
    private LinearLayout mLlMusic;
    private RelativeLayout mRlMusic;
    private TextView mTvMusicCurrentTime;
    private TextView mTvMusicDuration;
    private TextView mTvMusicName;
    private LinearLayout mLlMusicControl;
    private ImageView mIvMusicPlayOrPause;
    private ImageView mIvMusicStop;
    private String mMusicFileName;
    private boolean IsPlaying;
    private String mMusicCurrentPositionTime;
    private boolean cutNet;
    private boolean registerTag;
    private ShaderProgressBar mSpbMusic;
    private AlertDialog mOperationMenuDialog;
    private List<OperationMenuBean> mOperationMenuBeanList;
    private boolean isActionMove;
    private String mOperatedUserId;
    private boolean isOperationMenuDialog;
    private int mAnchorID;
    private boolean isLimitTalkAll;
    private String mAgoraLogPath;
    private String mRecordKey;
    private long mAnchorLeaveChannelTime;
    private OnClickListener mOnPanelClickListener;
    private int mTeacherCurrentPage = 1;
    private boolean mSyncPage;
    private DragFrameLayout mFlVideoStreamShow;
    private boolean mVideoStreamShow;
    private String mVideoStreamPath;
    private FragmentManager mFragmentManager;
    private int mRemoteVideoContainerWidth;
    private String mFilePath;
    private boolean isInspectorFirstSendMsg = true;
    private AlertDialog mInspectorSendMsgDialog;
    private double mClickLastTime;
    private boolean isMultiVideoSwitch;
    private List<String> mUserIdLists;
    private int mCurrentMultiVideoNum;
    private LinearLayout mLlGuideView;
    private ImageView mIvGuideClose;
    private RelativeLayout mRlVideoIndicator;
    private LinearLayout mLlVideoIndicator;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (savedInstanceState != null) {
            mFilePath = savedInstanceState.getString("take_photo_file_path");
        }

        mContext = this;
        AgoraApplication.getInstance().addActivity(this);
        Fresco.initialize(this);

        token = getIntent().getStringExtra("token");

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        /*平板-手机*/
        setContentView(isTabDevice() ? R.layout.activity_course_pad : R.layout.activity_channel_3b);

        bitmapUtils = new BitmapUtils(VideoActivity.this);
        mGson = new Gson();
        map = new HashMap<>();
        mDownLoadMusic = new DownLoadMusic(this);

        getPermission();

        initView();

        getData();
        //实例化汉字转拼音类
        mCharacterParser = CharacterParser.getInstance();

        mPinyinComparator = new PinyinComparator();

        //创建rtcEngine实例
        //setupRtcEngine();

        am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        am.setStreamVolume(AudioManager.STREAM_VOICE_CALL, 3, 0);

        registerVolumeChangeReceiver();

        registerWifiStrenghtReceiver();
        //悬浮菜单
        menu_5();
        //空白页
        SharedPreferencesUtils.setParam(this,"1", fileDirWhiteBorad);
        SharedPreferencesUtils.setParam(this,"1" + "pagenum", 10);

        //监听
        initListener();
        //获取计时器控件高度
        getTimerViewHeight();
        //打开定时器，执行操作,设置计时器动画
        timerHandler.postDelayed(runnable, 5000);

        mRemoteUserViewWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 150,
                getResources().getDisplayMetrics());

        mRemoteUserViewH = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100,
                getResources().getDisplayMetrics());

        xyPaint = new ObjData(x, y);
        xyPaint1 = new ObjData(x, y);

        // 设置教室名称
        //mTimerView.setTitleText(roomName);
        switch (mRoomType) {
            case 1:
                mTimerView.setImage(R.drawable.bar_1_v_1_class);
                break;
            case 2:
                mTimerView.setImage(R.drawable.bar_small_class);
                break;
            case 3:
                mTimerView.setImage(R.drawable.bar_large_class);
                break;
        }
    }

    private boolean isTabDevice() {

        return (getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    public void getData(){
        uri = getIntent().getData();

        if (uri != null) {
            setupUriRtcEngine();
            isVoucherJump = true;
            //协议跳转
            LogUtil.i("Test", "收到的协议信息_" + uri.toString());
            try {
                FileLogUtils.init(this);
                FileLogUtils.write("协议跳转uri " + uri.toString());
                browser2app();
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            //创建rtcEngine实例
            setupRtcEngine();
            isVoucherJump = false;

            String urlInfo = getIntent().getStringExtra("urlInfo");

            LogUtil.i(TAG, "urlInfo " + urlInfo);
            FileLogUtils.write("CourseVoucher: " + urlInfo);
            Logger.json(urlInfo);

            try {
                courseinfojson = new JSONObject(urlInfo);
                mUserID = courseinfojson.getInt("UserID");
                mUserName = courseinfojson.getString("UserName");
                mUserType = courseinfojson.getInt("UserType");
                String extKey = courseinfojson.getString("ExtKey");
                getRoomInfo(extKey);

                FileLogUtils.write("CourseVoucher: " + courseinfojson.toString());

                if (courseinfojson.has("RoomInfo")) {
                    JSONObject roomInfo = courseinfojson.getJSONObject("RoomInfo");

                    mHostID = roomInfo.getInt("HostID");
                    mAnchorID = mHostID;

                    mRoomType = roomInfo.getInt("RoomType");

                    mRoomID = roomInfo.getInt("RoomID");

                    roomName = roomInfo.getString("RoomName");

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            doRegister(mUserID, mUserName, mUserType);
                        }
                    }).start();

                    mCatalogLists = new ArrayList<>();
                    CatalogBean catalogBean = new CatalogBean("Default WitheBoard",
                                                              Constant.WHITEBOARDFILEDIR, "10", 1,
                                                              1);
                    catalogBean.setFileType("JPG");
                    mCatalogLists.add(
                            catalogBean);

                    if (courseinfojson.has("FileInfo")) {
                        JSONArray jarray = courseinfojson.getJSONArray("FileInfo");
                        FileInfo_list = new ArrayList<FileInfo>();
                        bookInfoList = new ArrayList<FileInfo>();
                        for (int i = 0; i < jarray.length(); i++) {
                            JSONObject mFileInfo = jarray.getJSONObject(i);
                            FileInfo fileinfo = mGson.fromJson(mFileInfo.toString(), FileInfo.class);
                            FileInfo_list.add(fileinfo);
                            /***
                             * 存FileInfo信息
                             */
                            mFileID = fileinfo.getFileID();
                            SharedPreferencesUtils.setParam(VideoActivity.this, mFileID + "", fileinfo.getFileDir());
                            SharedPreferencesUtils.setParam(VideoActivity.this, mFileID+"pagenum", Integer.parseInt(fileinfo.getPageNums()));
                            LogUtil.i(TAG, "存FileInfo信息: " + mFileID + "---" + FileInfo_list.get(i).getFileDir());
                        }
                        mp3list = new ArrayList<String>();
                        if (null != FileInfo_list) {
                            LogUtil.i(TAG, "FileInfo_list " + FileInfo_list.size());
                            for (int i = 0; i < FileInfo_list.size(); i++) {
                                SharedPreferencesUtils.setParam(this, mFileID + "", FileInfo_list.get(i).getFileDir());
                                SharedPreferencesUtils.setParam(this, FileInfo_list.get(i).getFileID() + "name", FileInfo_list.get(i).getFileName());

                                if (FileInfo_list.get(i).getFileName().contains(".mp3") ||
                                        FileInfo_list.get(i).getFileName().contains(".wav") ||
                                        FileInfo_list.get(i).getFileName().contains(".wma")) {

                                    String mp3Url = Constant.getMP3URL() + FileInfo_list.get(i).getFileDir() + "/1.mp3";

                                    LogUtil.e("mp3Url", mp3Url);

                                    mp3list.add(FileInfo_list.get(i).getFileID() + "");

                                    String filepath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/download" + "/" + FileInfo_list.get(i).getFileDir() + ".mp3";

                                    File file = new File(filepath);
                                    Logger.i("filepath " + file.toString());
                                    if (!file.exists()) {
                                        Logger.e("filepath不存在 要下载");
                                        mDownLoadMusic.downMusic(mp3Url, FileInfo_list.get(i).getFileDir() + ".mp3");
                                    } else {
                                        Logger.e("filepath存在 无需下载");
                                        hideLoadProgress();
                                    }

                                } else {//教材部分
                                    bookInfoList.add(FileInfo_list.get(i));
                                    if(0==bookInfoList.size()){
                                        hideLoadProgress();
                                    }
                                }
                            }
                        }
                        /****
                         * 通过获取到的数据，加载教材
                         */
                        //                        fileDir = FileInfo_list.get(0).getFileDir();
                        if (null != bookInfoList && bookInfoList.size() != 0) {
                            fileDir = bookInfoList.get(0).getFileDir();
                            mFileID = bookInfoList.get(0).getFileID();
                            mFileName = bookInfoList.get(0).getFileName();
                            mPageNums = Integer.parseInt(bookInfoList.get(0).getPageNums());
                        } else {
                            mPageNums=10;
                            mFileID = 1;
                            fileDir = fileDirWhiteBorad;
                        }

                        //mCatalogLists = new ArrayList<>();
                        //mCatalogLists.add(new CatalogBean("Default WitheBoard", Constant.WHITEBOARDFILEDIR, "10", 1, 1));
                        for (int i= 0; i < FileInfo_list.size(); i++) {
                            String fileName = FileInfo_list.get(i).getFileName();
                            String fileDir = "IdHYwoLGnCVXctW";
                            if (fileName.contains(".mp3") || fileName.contains(".wav") || fileName.contains(
                                    ".wma"))
                            {
                            } else {
                                fileDir = FileInfo_list.get(i).getFileDir();
                            }
                            String pageNums = FileInfo_list.get(i).getPageNums();
                            int fileId = FileInfo_list.get(i).getFileID();
                            CatalogBean jpgCatalogBean = new CatalogBean(fileName, fileDir, pageNums,
                                                                       1, fileId);
                            jpgCatalogBean.setFileType("JPG");
                            mCatalogLists.add(jpgCatalogBean);
                        }

                        /***
                         * 拼接成第一个教材地址URL
                         */
                        mUrl1 = Constant.getDocUrl() + fileDir + "/" + "1.jpg";
                        LogUtil.i(TAG, "第一个教材地址URL: " + mUrl1);
                        LogUtil.i(TAG, "第一个教材地址fileDir: " + fileDir);

                    }else{//什么都没有的时候加载白板页面
                        mUrl1 = Constant.getDocUrl() + fileDirWhiteBorad + "/" + currentPage +".jpg";
                        mPageNums=10;
                        mFileID = 1;
                        fileDir = fileDirWhiteBorad;
                    }
                    /***
                     * 访问网络，加载教材图片
                     */
                    LogUtil.i(TAG, "1111");
                    loadImageBitmap(mUrl1);
                    LogUtil.i(TAG, "loadImage默认登录方式打开第一张教材地址 " + mUrl1);

                    mClient = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();

                    mH5List = new ArrayList<>();
                    if (courseinfojson.has("HtmlFileInfo")) {
                        JSONArray htmlFileInfo = courseinfojson.getJSONArray("HtmlFileInfo");

                        for (int i = 0; i < htmlFileInfo.length(); i++) {
                            JSONObject jsonObject = htmlFileInfo.getJSONObject(i);
                            FileInfo fileInfo = mGson.fromJson(jsonObject.toString(), FileInfo.class);
                            mH5List.add(fileInfo);
                            FileInfo_list.add(fileInfo);
                            String filename = fileInfo.getFileName();
                            String filedir = fileInfo.getFileDir();
                            String pagenum = fileInfo.getPageNums();
                            int fileid = fileInfo.getFileID();
                            CatalogBean h5CatalogBean = new CatalogBean(filename, filedir, pagenum,
                                                                       1, fileid);
                            h5CatalogBean.setFileType("H5");
                            mCatalogLists.add(h5CatalogBean);
                        }
                    }

                    if (mH5List.size() > 0) {
                        startWebMode(true);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                OpenWebCommandBean.MessageBean messageBean = new OpenWebCommandBean.MessageBean();
                                OpenWebCommandBean.MessageBean.WhiteboardBean whiteboardBean = new OpenWebCommandBean.MessageBean.WhiteboardBean();

                                mFileID = mH5List.get(0).getFileID();
                                fileDir = mH5List.get(0).getFileDir();
                                whiteboardBean.setFilename(mH5List.get(0).getFileName());
                                whiteboardBean.setFiledir(mH5List.get(0).getFileDir());
                                whiteboardBean.setDocserver(Constant.getH5BASEURL());
                                whiteboardBean.setSubcommand("openweb");
                                whiteboardBean.setCurrentpage(1);
                                whiteboardBean.setCurrentaction(0);
                                whiteboardBean.setPagenum(0);
                                whiteboardBean.setFileid(mFileID);

                                messageBean.setType("whiteboard");
                                messageBean.setWhiteboard(whiteboardBean);
                                openWeb(messageBean);
                            }
                        });
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if (isTabDevice()) {
            //平板设备
            //显示服务器时间
            verifyConnectionTime("time", 0);
        }

        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("Version", Info.APIVERSION);
        params.addBodyParameter("RoomID", String.valueOf(mRoomID));
        VerificationKeyUtils keyUtils = new VerificationKeyUtils();
        String verificationKey = keyUtils.getVerificationKey(Info.MECHANISM_ID);
        params.addBodyParameter("VerificationKey", verificationKey);

        LogUtil.e("getRemarks", "Version=" + Info.APIVERSION + "&RoomID=" + mRoomID + "&VerificationKey=" + verificationKey);
        LogUtil.e("getRemarks", "url:" + Constant.getRemarks());

        httpUtils.send(HttpRequest.HttpMethod.POST, Constant.getRemarks(), params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                if (mGson == null) {
                    mGson = new Gson();
                }
                RemarksInfoBean remarksInfoBean = mGson.fromJson(responseInfo.result, RemarksInfoBean.class);

                if (remarksInfoBean.isResult()) {
                    mRoomRemarks = remarksInfoBean.getRemarks();
                } else {
                    mRoomRemarks = getResources().getString(R.string.course_whiteboard_no_remarks);
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
            }
        });
    }


    private void openWeb(final OpenWebCommandBean.MessageBean openWebBean) {
        try {
            final OpenWebCommandBean.MessageBean.WhiteboardBean whiteboard = openWebBean.getWhiteboard();
            String url = Constant.getH5BASEURL() + whiteboard.getFiledir() + "/1.html";

            LogUtil.e("weburl", url);
            mWebView.loadUrl(url);
            isWebLoaded = false;
            isWebReload = false;

            String filename = openWebBean.getWhiteboard().getFilename();

            if (filename.contains(".zip")) {
                mFileID = openWebBean.getWhiteboard().getFileid();
                currentPage = openWebBean.getWhiteboard().getCurrentpage();
                mTeacherCurrentPage = currentPage;
                fileDir = openWebBean.getWhiteboard().getFiledir();

                //飞博课件
                isZipTextBook = true;

                showZipHtml();

            } else {
                mWebView.setWebChromeClient(new WebChromeClient(){

                    @Override
                    public void onProgressChanged(WebView view, int newProgress) {
                        if (newProgress == 100 && isWebMode && !isWebLoaded) {
                            isWebLoaded = true;
                            mWebView.postDelayed(new Runnable() {
                                @RequiresApi(api = Build.VERSION_CODES.KITKAT)
                                @Override
                                public void run() {
                                    mWebView.evaluateJavascript("javascript:Presentation.GetContentDetails()", new ValueCallback<String>() {
                                        @Override
                                        public void onReceiveValue(String s) {
                                            LogUtil.e("js1", "contentDetails:" + s);
                                            if (s != null) {
                                                try {
                                                    JSONObject jsonObject = new JSONObject(s);
                                                    mPageNums = jsonObject.getInt("TotalSlides");
                                                    int contentWidth = jsonObject.getInt("Width");
                                                    int contentHeight = jsonObject.getInt("Height");

                                                    if (contentWidth == 0 && contentHeight == 0) {
                                                        run();
                                                    } else {
                                                        mFileID = whiteboard.getFileid();
                                                        currentPage =whiteboard.getCurrentpage();
                                                        mFileName = whiteboard.getFilename();
                                                        mTeacherCurrentPage = currentPage;
                                                        fileDir = whiteboard.getFiledir();
                                                        final int currentaction = whiteboard.getCurrentaction();
                                                        LogUtil.e("js1",
                                                                  "currentaction:" + currentaction + "currentPage" + currentPage);
                                                        mWebView.postDelayed(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                mWebView.loadUrl(
                                                                        "javascript:Presentation.JumpToAnim(" + currentaction + "," + currentPage + ",1)");
                                                            }
                                                        }, 200);

                                                        mPageText.setText(currentPage + "/" + mPageNums);

                                                        boolean isExist = false;
                                                        for (CatalogBean catalogList : mCatalogLists) {
                                                            if (catalogList.getFileId() == mFileID) {
                                                                isExist = true;
                                                            }
                                                        }

                                                        if (!isExist) {
                                                            CatalogBean catalogBean = new CatalogBean();
                                                            catalogBean.setCurrentaction(0);
                                                            catalogBean.setFileName(mFileName);
                                                            catalogBean.setFileId(mFileID);
                                                            catalogBean.setPageNums(String.valueOf(mPageNums));
                                                            catalogBean.setCurrentpage(currentPage);
                                                            catalogBean.setFileType("H5");
                                                            mCatalogLists.add(catalogBean);
                                                        }
                                                        mWebView.initData(mFileID, currentPage, contentWidth,
                                                                          contentHeight);
                                                        initWebMedia();
                                                    }
                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                }
                                            } else {
                                                run();
                                            }
                                        }
                                    });
                                }
                            }, 200);
                        }
                    }

                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initWebMedia() {

        mWebView.post(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void run() {
                mWebView.evaluateJavascript(
                        "javascript:document.getElementsByTagName(\"audio\").length;", new ValueCallback<String>() {
                            @Override
                            public void onReceiveValue(String value) {
                                if (value != null && !value.equals("")) {
                                    LogUtil.e("webmedia", "audioNum:" + value);
                                    int audioNum = Integer.parseInt(value);

                                    for (int i = 0; i < audioNum; i++) {
                                        mWebView.evaluateJavascript(
                                                "javascript:document.getElementsByTagName(\"audio\")[" + i + "].id;", new ValueCallback<String>() {
                                                    @Override
                                                    public void onReceiveValue(String value) {
                                                        if (value != null && !value.equals("\"\"")) {
                                                            value = value.replace("\"", "");
                                                            LogUtil.e("webmedia", "audioID:" + value);
                                                            String substring = value.substring(1);
                                                            LogUtil.e("webmedia", "substring:" + substring);
                                                            mWebView.loadUrl("javascript:document.getElementById(\"" + substring + "\").onclick=function(){console.log(\"qcloud-" + value + "\")};");
                                                        }
                                                    }
                                                });
                                    }
                                }
                            }
                        });

                mWebView.evaluateJavascript(
                        "javascript:document.getElementsByTagName(\"video\").length;", new ValueCallback<String>() {
                            @Override
                            public void onReceiveValue(String value) {
                                if (value != null && !value.equals("")) {
                                    LogUtil.e("webmedia", "videoNum:" + value);
                                    final int videoNum = Integer.parseInt(value);

                                    mWebView.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            for (int i = 0; i < videoNum; i++) {
                                                mWebView.evaluateJavascript(
                                                        "javascript:document.getElementsByTagName(\"video\")[" + i + "].id;", new ValueCallback<String>() {
                                                            @Override
                                                            public void onReceiveValue(String value) {
                                                                if (value != null && !value.equals("\"\"")) {
                                                                    value = value.replace("\"", "");
                                                                    LogUtil.e("webmedia", "videoID" + value);
                                                                    String substring = value.substring(1);
                                                                    LogUtil.e("webmedia", "substring:" + substring);

                                                                    mWebView.loadUrl("javascript:document.getElementById(\"" + value + "\").addEventListener('play',function(){console.log(\"qcloud-" + value +"\")});");
                                                                    mWebView.loadUrl("javascript:document.getElementById(\"" + value + "\").addEventListener('pause',function(){console.log(\"qcloud-" + value +"\")});");
                                                                }
                                                            }
                                                        });
                                            }
                                        }
                                    });
                                }
                            }
                        });
            }
        });

        mWebView.setWebChromeClient(new WebChromeClient(){

            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {

                if (consoleMessage != null) {
                    String message = consoleMessage.message();
                    LogUtil.e("onConsoleMessage", message);

                    if (message.startsWith("qcloud-")) {
                        final String mediaID = message.replace("qcloud-", "");
                        LogUtil.e("onConsoleMessage", "mediaID:" + mediaID);

                        mWebView.evaluateJavascript(
                                "javascript:document.getElementById(\"" + mediaID+ "\").paused;", new ValueCallback<String>() {
                                    @Override
                                    public void onReceiveValue(String value) {
                                        if (value != null) {
                                            String action = "";

                                            if (value.equals("true")) {
                                                action = "pause";
                                            } else if (value.equals("false")) {
                                                action = "play";
                                            }

                                            if (mUserID == mHostID) {
                                                WebMediaBean webMediaBean = new WebMediaBean();
                                                WebMediaBean.MessageBean messageBean = new WebMediaBean.MessageBean();
                                                WebMediaBean.MessageBean.WhiteboardBean whiteboardBean = new WebMediaBean.MessageBean.WhiteboardBean();

                                                whiteboardBean.setFileid(mFileID);
                                                whiteboardBean.setCurrentpage(currentPage);
                                                whiteboardBean.setMediaid(mediaID);
                                                whiteboardBean.setAction(action);
                                                whiteboardBean.setSubcommand("webmedia");

                                                messageBean.setWhiteboard(whiteboardBean);
                                                messageBean.setType("whiteboard");
                                                webMediaBean.setMessage(messageBean);

                                                final String jsonString = mGson.toJson(webMediaBean);
                                                LogUtil.e("webmedia", jsonString);
                                                ThreadUtils.runOnSubThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        egine.SendGroupMessage(Constant.WHITEBOARDMSGTYPE, mGroup, jsonString);
                                                    }
                                                });
                                            }
                                        }
                                    }
                                });

                    }
                }

                return super.onConsoleMessage(consoleMessage);
            }
        });
    }

    /*web课件切换*/
    public void switchAndShareWeb(int fileID, String filedir, final String fileName) {
        mFileID = fileID;
        fileDir = filedir;

        for (CatalogBean h5CatlogList : mCatalogLists) {
            if (fileID == h5CatlogList.getFileId()) {
                currentPage = h5CatlogList.getCurrentpage();
                mCurrentaction = h5CatlogList.getCurrentaction();
                if (h5CatlogList.getPageNums() != null) {
                    mPageNums = Integer.parseInt(h5CatlogList.getPageNums());
                }

                LogUtil.e("swtich", currentPage + " ," + mCurrentaction + " ," + mPageNums);
            }
        }

        String url = Constant.getH5BASEURL() + fileDir + "/1.html";

        mWebView.loadUrl(url);
        isWebLoaded = false;
        isWebReload = false;

        if (fileName.contains(".zip")) {

            //飞博课件
            isZipTextBook = true;

            showZipHtml();

            OpenWebCommandBean.MessageBean.WhiteboardBean whiteboardBean = new OpenWebCommandBean.MessageBean.WhiteboardBean();

            whiteboardBean.setFileid(mFileID);
            whiteboardBean.setFiledir(fileDir);
            whiteboardBean.setFilename(fileName);
            whiteboardBean.setPagenum(mPageNums);
            whiteboardBean.setDocserver(Constant.getH5BASEURL());
            whiteboardBean.setCurrentaction(mCurrentaction);
            whiteboardBean.setCurrentpage(currentPage);
            whiteboardBean.setSubcommand("openweb");

            OpenWebCommandBean.MessageBean openWebMessageBean = new OpenWebCommandBean.MessageBean();
            openWebMessageBean.setType("whiteboard");
            openWebMessageBean.setWhiteboard(whiteboardBean);

            if (mUserID == mHostID || mAnchor) {
                OpenWebCommandBean openWebCommandBean = new OpenWebCommandBean();
                openWebCommandBean.setMessage(openWebMessageBean);
                final String msg = new Gson().toJson(openWebCommandBean);
                ThreadUtils.runOnSubThread(new Runnable() {
                    @Override
                    public void run() {
                        egine.SendGroupMessage(Constant.WHITEBOARDMSGTYPE, mGroup, msg);
                    }
                });
            }
        } else {
            mWebView.setWebChromeClient(new WebChromeClient(){

                @Override
                public void onProgressChanged(WebView view, int newProgress) {
                    super.onProgressChanged(view, newProgress);
                    LogUtil.e("js2", "newProgress:" + newProgress);

                    if (newProgress == 100 && !isWebLoaded) {
                        isWebLoaded = true;
                        mWebView.postDelayed(new Runnable() {
                            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
                            @Override
                            public void run() {
                                mWebView.evaluateJavascript("javascript:Presentation.GetContentDetails()", new ValueCallback<String>() {
                                    @Override
                                    public void onReceiveValue(String s) {
                                        LogUtil.e("js2", "contentDetails:" + s);
                                        if (s == null) {
                                            run();
                                        } else {
                                            try {
                                                JSONObject jsonObject = new JSONObject(s);
                                                mPageNums = jsonObject.getInt("TotalSlides");
                                                int contentWidth = jsonObject.getInt("Width");
                                                int contentHeight = jsonObject.getInt("Height");

                                                if (contentWidth == 0 && contentHeight == 0) {
                                                    run();
                                                } else {
                                                    mPageText.setText(currentPage + "/" + mPageNums);
                                                    mArrowLeft.setVisibility(currentPage > 1 ? View.VISIBLE : View.GONE);
                                                    mArrowRight.setVisibility(currentPage < mPageNums ? View.VISIBLE : View.GONE);

                                                    OpenWebCommandBean.MessageBean.WhiteboardBean whiteboardBean = new OpenWebCommandBean.MessageBean.WhiteboardBean();

                                                    whiteboardBean.setFileid(mFileID);
                                                    whiteboardBean.setFiledir(fileDir);
                                                    whiteboardBean.setFilename(fileName);
                                                    whiteboardBean.setPagenum(mPageNums);
                                                    whiteboardBean.setDocserver(Constant.getH5BASEURL());
                                                    whiteboardBean.setCurrentaction(mCurrentaction);
                                                    whiteboardBean.setCurrentpage(currentPage);
                                                    whiteboardBean.setSubcommand("openweb");

                                                    OpenWebCommandBean.MessageBean openWebMessageBean = new OpenWebCommandBean.MessageBean();
                                                    openWebMessageBean.setType("whiteboard");
                                                    openWebMessageBean.setWhiteboard(whiteboardBean);

                                                    if (mUserID == mHostID || mAnchor) {
                                                        OpenWebCommandBean openWebCommandBean = new OpenWebCommandBean();
                                                        openWebCommandBean.setMessage(openWebMessageBean);
                                                        final String jsonString = new Gson().toJson(openWebCommandBean);
                                                        ThreadUtils.runOnSubThread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                if (egine != null) {
                                                                    egine.SendGroupMessage(Constant.WHITEBOARDMSGTYPE, mGroup, jsonString);
                                                                }
                                                            }
                                                        });
                                                    }

                                                    for (CatalogBean h5CatlogList : mCatalogLists) {
                                                        if (mFileID == h5CatlogList.getFileId()) {
                                                            h5CatlogList.setPageNums(String.valueOf(mPageNums));
                                                        }
                                                    }

                                                    mWebView.initData(mFileID, currentPage, contentWidth, contentHeight);

                                                    initWebMedia();

                                                    mWebView.post(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            LogUtil.e("swtich1", currentPage + " ," + mCurrentaction + " ," + mPageNums);
                                                            mWebView.loadUrl(
                                                                    "javascript:Presentation.JumpToAnim(" + mCurrentaction + "," + currentPage + ",1)");
                                                        }
                                                    });
                                                }
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }
                                });
                            }
                        }, 200);
                    }
                }
            });
        }
    }

    private void showZipHtml(){
        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {

                if (!isWebLoaded && newProgress >= 80) {
                    isWebLoaded = true;
                    LogUtil.e("consoleMessage", "progress:" + newProgress);
                    mWebView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mWebView.loadUrl(
                                    "javascript:window.addEventListener(\"message\",function(e){console.log(e.data)});");
                        }
                    }, 0);
                }
            }

            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                try {
                    if (consoleMessage != null) {
                        String consoleMsg = consoleMessage.message().trim();
                        LogUtil.e("consoleMessage0", consoleMsg);
                        if (consoleMsg.startsWith("{") && consoleMsg.endsWith("}")) {

                            JSONObject jsonObject = new JSONObject(consoleMsg);
                            String method = jsonObject.getString("method");

                            if (method.equals("onPagenum")) {
                                mPageNums = jsonObject.getInt("totalPages");
                            } else if (method.equals("onLoadComplete")) {
                                isWebLoaded = true;
                                double coursewareRatio = 16 / 9.0d;

                                if (jsonObject.has("coursewareRatio")) {
                                    coursewareRatio = jsonObject.getDouble("coursewareRatio");
                                    Log.e("coursewareRatio", "coursewareRatio:" + coursewareRatio);
                                }

                                if (mWebViewWidth == 0 && mWebViewHeight == 0) {
                                    mWebViewWidth = mWebView.getMeasuredWidth();
                                    mWebViewHeight = mWebView.getMeasuredHeight();
                                }

                                Log.e("measuredWidth", "measuredWidth:" + mWebViewWidth);
                                Log.e("measuredHeight", "measuredHeight:" + mWebViewHeight);

                                ViewParent parent = mWebView.getParent();

                                if (parent instanceof RelativeLayout) {
                                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mWebView
                                            .getLayoutParams();

                                    if (coursewareRatio == 4 / 3.0d) {
                                        Log.e("ratio", "ratio:" + 4 / 3.0d);

                                        if (mWebViewHeight < mWebViewWidth * 3 / 4) {
                                            int currentWidth = mWebViewHeight * 4 / 3;
                                            layoutParams.width = currentWidth;
                                            layoutParams.leftMargin = (mWebViewWidth - currentWidth) / 2;
                                        } else {
                                            int currentHeight = mWebViewWidth * 3 / 4;
                                            layoutParams.height = currentHeight;
                                            layoutParams.topMargin = (mWebViewHeight - currentHeight) / 2;
                                        }
                                        mWebView.setLayoutParams(layoutParams);
                                        mWebView.invalidate();

                                        mWebView.initData(mFileID, 1 , 800, 600, DrawableWebView.LocationMode.TOP);
                                    } else {
                                        layoutParams.width = mWebViewWidth;
                                        if (mWebViewHeight > mWebViewWidth) {
                                            layoutParams.height = mWebViewWidth;
                                            layoutParams.topMargin = (mWebViewHeight - mWebViewWidth) / 2;

                                        } else {
                                            layoutParams.height = mWebViewHeight;
                                            layoutParams.topMargin = 0;
                                        }

                                        mWebView.setLayoutParams(layoutParams);
                                        mWebView.invalidate();
                                        if (!isWebReload) {
                                            isWebReload = true;
                                            mWebView.reload();
                                        }

                                        mWebView.initData(mFileID, 1 , 980, 551);
                                    }
                                } else if(parent instanceof LinearLayout) {
                                    LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mWebView
                                            .getLayoutParams();

                                    if (coursewareRatio == 4 / 3.0d) {
                                        Log.e("ratio", "ratio:" + 4 / 3.0d);

                                        if (mWebViewHeight < mWebViewWidth * 3 / 4) {
                                            int currentWidth = mWebViewHeight * 4 / 3;
                                            layoutParams.width = currentWidth;
                                            layoutParams.leftMargin = (mWebViewWidth - currentWidth) / 2;
                                        } else {
                                            int currentHeight = mWebViewWidth * 3 / 4;
                                            layoutParams.height = currentHeight;
                                            layoutParams.topMargin = (mWebViewHeight - currentHeight) / 2;
                                        }
                                        mWebView.setLayoutParams(layoutParams);
                                        mWebView.invalidate();

                                        mWebView.initData(mFileID, 1 , 800, 600, DrawableWebView.LocationMode.TOP);
                                    } else {
                                        layoutParams.width = mWebViewWidth;
                                        if (mWebViewHeight > mWebViewWidth) {
                                            layoutParams.height = mWebViewWidth;
                                            layoutParams.topMargin = (mWebViewHeight - mWebViewWidth) / 2;

                                        } else {
                                            layoutParams.height = mWebViewHeight;
                                            layoutParams.topMargin = 0;
                                        }

                                        mWebView.setLayoutParams(layoutParams);
                                        mWebView.invalidate();
                                        if (!isWebReload) {
                                            isWebReload = true;
                                            mWebView.reload();
                                        }

                                        mWebView.initData(mFileID, 1 , 980, 551);
                                    }
                                } else if (parent instanceof FrameLayout) {
                                    FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mWebView
                                            .getLayoutParams();

                                    if (coursewareRatio == 4 / 3.0d) {
                                        Log.e("ratio", "ratio:" + 4 / 3.0d);

                                        if (mWebViewHeight < mWebViewWidth * 3 / 4) {
                                            int currentWidth = mWebViewHeight * 4 / 3;
                                            layoutParams.width = currentWidth;
                                            layoutParams.leftMargin = (mWebViewWidth - currentWidth) / 2;
                                        } else {
                                            int currentHeight = mWebViewWidth * 3 / 4;
                                            layoutParams.height = currentHeight;
                                            layoutParams.topMargin = (mWebViewHeight - currentHeight) / 2;
                                        }
                                        mWebView.setLayoutParams(layoutParams);
                                        mWebView.invalidate();

                                        mWebView.initData(mFileID, 1 , 800, 600, DrawableWebView.LocationMode.TOP);
                                    } else {
                                        layoutParams.width = mWebViewWidth;
                                        if (mWebViewHeight > mWebViewWidth) {
                                            layoutParams.height = mWebViewWidth;
                                            layoutParams.topMargin = (mWebViewHeight - mWebViewWidth) / 2;

                                        } else {
                                            layoutParams.height = mWebViewHeight;
                                            layoutParams.topMargin = 0;
                                        }

                                        mWebView.setLayoutParams(layoutParams);
                                        mWebView.invalidate();
                                        if (!isWebReload) {
                                            isWebReload = true;
                                            mWebView.reload();
                                        }

                                        mWebView.initData(mFileID, 1 , 980, 551);
                                    }
                                }

                                if (currentPage != 1) {
                                    mWebView.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            String jumpConsole = "{\"method\":\"onJumpPage\",\"toPage\":" + currentPage + "}";
                                            LogUtil.e("jumpConsole", jumpConsole);
                                            mWebView.loadUrl("javascript:postMessage('" + jumpConsole + "','*');");
                                        }
                                    }, 1500);
                                }

                                return true;
                            } else if (method.equals("onJumpPage")) {
                                currentPage = jsonObject.getInt("toPage");
                            } else if (method.equals("onPageup")) {
                                if (currentPage > 1) {
                                    currentPage--;
                                }
                            } else if (method.equals("onPagedown")) {
                                if (currentPage < mPageNums) {
                                    currentPage++;
                                }
                            } else if (method.equals("onFileMessage")) {
                                if ((jsonObject.has("posx") && jsonObject.has("posy"))
                                        && (jsonObject.isNull("posx") || jsonObject.isNull("posy"))) {
                                    return true;
                                }
                            }

                            if (method.equals("onPagenum") || method.equals("onJumpPage") || method
                                    .equals("onPageup") || method.equals("onPagedown"))
                            {
                                mPageText.setText(currentPage + "/" + mPageNums);
                                mArrowLeft.setVisibility(currentPage > 1 ? View.VISIBLE : View.GONE );
                                mArrowRight.setVisibility(currentPage < mPageNums ? View.VISIBLE : View.GONE );

                                for (CatalogBean h5CatlogList : mCatalogLists) {
                                    if (mFileID == h5CatlogList.getFileId()) {
                                        h5CatlogList.setCurrentaction(0);
                                        h5CatlogList.setCurrentpage(currentPage);
                                    }
                                }

                                LogUtil.e("changePage", mFileID + ";;;" + currentPage);
                                mWebView.changePage(mFileID, currentPage);

                                if (method.equals("onPageup") || method.equals("onPagedown")) {
                                    consoleMsg = "{\"method\":\"onJumpPage\",\"toPage\":" + currentPage + "}";
                                }
                            }

                            if (mUserType == 1 && isWebLoaded) {
                                Map<String, Object> wbData = new HashMap<String, Object>();
                                wbData.put("fileid", mFileID);
                                wbData.put("currentpage", currentPage);
                                wbData.put("console", consoleMsg);
                                wbData.put("subcommand", "webconsole");
                                JSONObject wbObject = new JSONObject(wbData);
                                Map<String, Object> typeData = new HashMap<String, Object>();
                                typeData.put("type", "whiteboard");
                                typeData.put("whiteboard", wbObject);
                                JSONObject typeObject = new JSONObject(typeData);
                                Map<String, Object> msgData = new HashMap<String, Object>();
                                msgData.put("message", typeObject);
                                JSONObject msgObject = new JSONObject(msgData);

                                final String msg = msgObject.toString();
                                LogUtil.e("IMHelper", msg);
                                ThreadUtils.runOnSubThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        egine.SendGroupMessage(Constant.WHITEBOARDMSGTYPE, mGroup, msg);
                                    }
                                });
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return super.onConsoleMessage(consoleMessage);
            }
        });
    }

    /**
     * 开启web模式
     * @param enable
     */
    private void startWebMode(boolean enable) {
        isWebMode = enable;

        mFrameLayout.setVisibility(enable ? View.GONE : View.VISIBLE);
        mWebView.setVisibility(enable ? View.VISIBLE : View.GONE);
    }

    /**
     * web手动操作
     * @param type
     */
    public void webTurnOperate(String type){
        if (isZipTextBook) {
            //feibo
            if ("webprev".equals(type)) {
                mWebView.post(new Runnable() {
                    @Override
                    public void run() {
                        mWebView.loadUrl("javascript:postMessage('{\"method\":\"onPageup\"}','*');");
                    }
                });
            } else if ("webnext".equals(type)) {
                mWebView.post(new Runnable() {
                    @Override
                    public void run() {
                        mWebView.loadUrl("javascript:postMessage('{\"method\":\"onPagedown\"}','*');");
                    }
                });
            }
        } else {
            if ("webprev".equals(type)) {
                mWebView.post(new Runnable() {
                    @Override
                    public void run() {
                        mWebView.loadUrl("javascript:Presentation.Prev()");
                    }
                });
            } else if ("webnext".equals(type)) {
                mWebView.post(new Runnable() {
                    @Override
                    public void run() {
                        mWebView.loadUrl("javascript:Presentation.Next()");
                    }
                });
            }

            initWebMedia();

            mWebView.postDelayed(new Runnable() {
                @RequiresApi(api = Build.VERSION_CODES.KITKAT)
                @Override
                public void run() {

                    mWebView.evaluateJavascript("javascript:Presentation.CurrentStatus()", new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String s) {
                            try {
                                JSONObject jsonObject = new JSONObject(s);
                                currentPage = jsonObject.getInt("slide");
                                mCurrentaction = jsonObject.getInt("step");

                                mPageText.setText(currentPage + "/" + mPageNums);
                                mArrowLeft.setVisibility(currentPage > 1 ? View.VISIBLE : View.GONE);
                                mArrowRight.setVisibility(currentPage < mPageNums ? View.VISIBLE : View.GONE);

                                for (CatalogBean h5CatlogList : mCatalogLists) {
                                    if (mFileID == h5CatlogList.getFileId()) {
                                        h5CatlogList.setCurrentaction(mCurrentaction);
                                        h5CatlogList.setCurrentpage(currentPage);
                                    }
                                }

                                mWebView.changePage(mFileID, currentPage);

                                if (mUserID == mHostID || mAnchor) {
                                    SendPageturnMessge.sendWebTurn(mFileID, currentPage, mCurrentaction, egine, mGroup);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }, 300);
        }
    }

    public void webTurn(WebTurnCommandBean.MessageBean webTurnBean) {
        WebTurnCommandBean.MessageBean.WhiteboardBean whiteboard = webTurnBean.getWhiteboard();
        mFileID = whiteboard.getFileid();
        currentPage = whiteboard.getCurrentpage();
        mTeacherCurrentPage = currentPage;
        final int currentaction = whiteboard.getCurrentaction();
        LogUtil.e("webturn", "currentaction" + currentaction + "currentpage" + currentPage);

        mArrowLeft.setVisibility(currentPage > 1 ? View.VISIBLE : View.GONE);
        mArrowRight.setVisibility(currentPage < mPageNums ? View.VISIBLE : View.GONE);

        mWebView.post(new Runnable() {
            @Override
            public void run() {
                mWebView.loadUrl(
                        "javascript:Presentation.JumpToAnim(" + currentaction + "," + currentPage + ",1)");
            }
        });

        for (CatalogBean h5CatlogList : mCatalogLists) {
            if (mFileID == h5CatlogList.getFileId()) {
                h5CatlogList.setCurrentaction(currentaction);
                h5CatlogList.setCurrentpage(currentPage);
            }
        }

        mWebView.changePage(mFileID, currentPage);
        mPageText.setText(currentPage + "/" + mPageNums);
    }

    /*网页跳转*/
    public void webJump(final int pageNum) {

        if (isZipTextBook) {
            String jumpConsole = "{\"method\":\"onJumpPage\",\"toPage\":" + pageNum + "}";
            mWebView.loadUrl("javascript:postMessage('" + jumpConsole + "','*');");
        } else {
            mWebView.post(new Runnable() {
                @Override
                public void run() {
                    mWebView.loadUrl("javascript:Presentation.GotoSlide(" + pageNum + ")");
                }
            });

            if (mUserID == mHostID || mAnchor) {
                SendPageturnMessge.sendWebTurn(mFileID, currentPage, 0, egine, mGroup);
            }
        }


        currentPage = pageNum;
        mWebView.changePage(mFileID, currentPage);

        for (CatalogBean h5CatlogList : mCatalogLists) {
            if (mFileID == h5CatlogList.getFileId()) {
                h5CatlogList.setCurrentaction(0);
                h5CatlogList.setCurrentpage(pageNum);
            }
        }
        mPageText.setText(pageNum + "/" + mPageNums);
    }

    private void getRoomInfo(String extKey) {
        VerificationKeyUtils keyUtils = new VerificationKeyUtils();
        String VerificationKey = keyUtils.getVerificationKey(Info.MECHANISM_ID);

        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("Version", Info.APIVERSION);
        params.addBodyParameter("URLID", extKey);
        params.addBodyParameter("VerificationKey", VerificationKey);

        Log.i(TAG,"getRoomInfo url:"+Constant.getEnterRoomCommand());
        Log.i(TAG, "getRoomInfo params,version:"+Info.APIVERSION+",urlId:"+extKey+",VerificationKey:"+VerificationKey);
        httpUtils.send(HttpRequest.HttpMethod.POST, Constant.getEnterRoomCommand(), params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {

                    Log.i("OnJoinGroup","getRoomInfo:"+responseInfo.result);
                    CommandInfoBean commandInfoBean = mGson.fromJson(responseInfo.result, CommandInfoBean.class);
                    if(commandInfoBean==null)
                    {
                        Log.e(TAG,"commandInfoBean is null");
                        return;
                    }
                    if (commandInfoBean.isResult()) {
                        String infostr = StringEncrypt.S1Decrypt(commandInfoBean.getCommand(), Info.Protocol_EncryptionKey);
                        JSONObject courseInfoJson = new JSONObject(infostr);

                        if (courseInfoJson.has("RoomInfo")) {
                            JSONObject roomInfo = courseInfoJson.getJSONObject("RoomInfo");

                            String roomID = roomInfo.getString("RoomID");
                            String roomExID = roomInfo.getString("RoomExID");
                            String hostID = roomInfo.getString("HostID");
                            String roomType = roomInfo.getString("RoomType");
                            String roomName = roomInfo.getString("RoomName");
                            String startTime = roomInfo.getString("StartTime");
                            String stopTime = roomInfo.getString("StopTime");
                            boolean needPassword = roomInfo.getBoolean("NeedPassword");
                            String password = roomInfo.getString("Password");
                            mVideoProfileType = roomInfo.getInt("VideoProfileType");

                            String[] startTimeStrs = startTime.split("/| |:");
                            String[] stopTimeStrs = stopTime.split("/| |:");
                            String start = String.format("%02d", Integer.parseInt(startTimeStrs[3])) + ":" + String.format("%02d", Integer.parseInt(startTimeStrs[4]));
                            String stop = String.format("%02d", Integer.parseInt(stopTimeStrs[3])) + ":" + String.format("%02d", Integer.parseInt(stopTimeStrs[4]));

                            String info = "";
                            if (isTabDevice()) {
                                //平板设备
                                //info = roomName + "/" + start + "~" + stop + "/" + getResources().getString(R.string.course_tool_label_roomid) + roomExID;
                                info = roomName;
                            } else {
                                info = roomName;
                            }

                            mTimerView.setTitleText(info);
                        }
                    }else {
                        mTimerView.setTitleText(roomName);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    mTimerView.setTitleText(roomName);
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                e.printStackTrace();
                mTimerView.setTitleText(roomName);
            }

        });
    }

    private void hideLoadProgress(){
        ThreadUtils.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                mProgressBar.setVisibility(View.GONE);
            }
        });
    }

    private void getPermission() {
        AndPermission.with(this)
                     .requestCode(REQUEST_CODE_PERMISSION_OTHER)
                     .permission(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                     // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框，避免用户勾选不再提示。
                     //                .rationale((requestCode, rationale) ->
                     //                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                     //                        AndPermission.rationaleDialog(LiveRoomActivity.this, rationale).show()
                     //                )
                     .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        AndPermission.rationaleDialog(VideoActivity.this, rationale).show();
                    }
                })
                     .send();
    }



    @PermissionYes(REQUEST_CODE_PERMISSION_OTHER)
    private void getMultiYes(List<String> grantedPermissions) {
        //Toast.makeText(this, "成功拿到所需权限", Toast.LENGTH_SHORT).show();
        setupUriRtcEngine();
    }

    @PermissionNo(REQUEST_CODE_PERMISSION_OTHER)
    private void getMultiNo(List<String> deniedPermissions) {
        Toast.makeText(this, getResources().getString(R.string.permission_access_failed), Toast.LENGTH_SHORT).show();

        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
            AndPermission.defaultSettingDialog(this, REQUEST_CODE_SETTING)
                         .setTitle(getResources().getString(R.string.friendship_tips))
                         .setMessage(getResources().getString(R.string.permissions_worning))
                         .setPositiveButton(getResources().getString(R.string.authorize_permissions))
                         .setNegativeButton(getResources().getString(R.string.denied_permissions), null)
                         .show();

            // 更多自定dialog，请看上面。
        }
    }

    //----------------------------------权限回调处理----------------------------------//

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
            grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        /**
         * 转给AndPermission分析结果。
         *
         * @param object     要接受结果的Activity、Fragment。
         * @param requestCode  请求码。
         * @param permissions  权限数组，一个或者多个。
         * @param grantResults 请求结果。
         */
        AndPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    private void registerWifiStrenghtReceiver() {
        mWifiChangeBroadcastReceiver = new WifiChangeBroadcastReceiver();
        IntentFilter wifiIntentFilter = new IntentFilter();
        wifiIntentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        wifiIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        wifiIntentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);

        registerReceiver(mWifiChangeBroadcastReceiver, wifiIntentFilter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_dialogue:
                processDialogueClick();
                break;

            case R.id.rl_member:
                processMemberClick();
                break;

            case R.id.ll_remote_video_container:
                long currentTimeMillis = System.currentTimeMillis();

                if (currentTimeMillis - mRemoteClickLastTime > 300) {
                    mRemoteClickLastTime = currentTimeMillis;
                } else {
                    processRemoteVideoContainerClick();
                }
                break;

            case R.id.raise_hand:
                processRaiseHandClick();
                break;

            case R.id.iv_music_play_pause:
                processMusicPlayPauseClick();
                break;

            case R.id.iv_music_stop:
                processMusicStopClick();
                break;

            case R.id.iv_guide_close:
                processGuideCloseClick();
                break;

            case R.id.iv_emoji:
                processChatIconClick();
                break;

            case R.id.btn_send:
                processSendClick();
                break;

            case R.id.rl_music:
                setAnimatorSet();
                break;

            case R.id.pageText:
                processPageClick();
                break;
            case R.id.arrow_left:
                if (cutNet) {
                    Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_net_cannot_use), Toast.LENGTH_SHORT).show();
                    return;
                }

                if (isWebMode) {
                    webTurnOperate("webprev");
                } else {
                    mTurnPage = true;
                    if (currentPage <= mPageNums && currentPage > 1) {
                        mArrowRight.setVisibility(View.VISIBLE);

                        mSyncPage = (mTeacherCurrentPage == currentPage);

                        currentPage--;

                        imageurl = Constant.getDocUrl() + fileDir + "/" + currentPage + ".jpg";
                        LogUtil.i(TAG, "←自己手动翻页地址  " + imageurl);

                        loadImageBitmap(imageurl);

                        if(mUserID == mHostID || mAnchor || mUserType == 3){
                            //只有主讲才能发送翻页命令
                            upLoadCurrentTextBook(fileDir, currentPage);
                        }

                        if (currentPage == 1) {
                            mArrowLeft.setVisibility(View.GONE);
                        }
                    }
                }

                break;
            case R.id.arrow_right:
                if (cutNet) {
                    Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_net_cannot_use), Toast.LENGTH_SHORT).show();
                    return;
                }

                if (isWebMode) {
                    webTurnOperate("webnext");
                } else {
                    mTurnPage = true;
                    if (currentPage >= 1 && currentPage < mPageNums) {
                        mArrowLeft.setVisibility(View.VISIBLE);

                        mSyncPage = (mTeacherCurrentPage == currentPage);

                        currentPage++;

                        imageurl = Constant.getDocUrl() + fileDir + "/" + currentPage + ".jpg";
                        LogUtil.i(TAG, "→自己手动翻页地址  " + imageurl);

                        loadImageBitmap(imageurl);

                        if(mUserID == mHostID || mAnchor || mUserType == 3){
                            //只有主讲才能发送翻页命令
                            upLoadCurrentTextBook(fileDir, currentPage);
                        }

                        if (currentPage == mPageNums) {
                            mArrowRight.setVisibility(View.GONE);
                        }
                    }
                }
                break;
        }
    }

    /*对话栏的点击*/
    private void processDialogueClick() {
        member_pressed = false;
        mIvMessage.setVisibility(View.GONE);

        mViewDialogue.setVisibility(View.VISIBLE);
        mSwipeRefreshChat.setVisibility(View.VISIBLE);
        mLvChatMember.setVisibility(View.VISIBLE);
        mViewMember.setVisibility(View.GONE);
        mLvMember.setVisibility(View.GONE);
        mClearEditText.setVisibility(View.GONE);

        if (mChatHistoryAdapter == null) {
            mChatHistoryAdapter = new ChatHistoryAdapter(VideoActivity.this, mChatMsgLists);
            mLvChatMember.setAdapter(mChatHistoryAdapter);
            mLvChatMember.setSelection(mChatHistoryAdapter.getCount());
        } else {
            mChatHistoryAdapter.updateData(mChatMsgLists);
            mLvChatMember.setSelection(mChatHistoryAdapter.getCount());
        }
    }

    /*成员栏的点击*/
    private void processMemberClick() {
        member_pressed = true;

        mViewMember.setVisibility(View.VISIBLE);
        mClearEditText.setVisibility(mRoomType == 3 ? View.VISIBLE : View.GONE);
        mLvMember.setVisibility(View.VISIBLE);
        mViewDialogue.setVisibility(View.GONE);
        mSwipeRefreshChat.setVisibility(View.GONE);
        mLvChatMember.setVisibility(View.GONE);

        if (userlist != null) {
            mSourceDateList = SortUtils.filledData(mCharacterParser, userlist);
            // 根据a-z进行排序源数据
            if (mSourceDateList != null) {
                Collections.sort(mSourceDateList, mPinyinComparator);
            }
            if (mSortMemberAdapter == null) {
                mSortMemberAdapter = new SortMemberAdapter(VideoActivity.this, mSourceDateList,
                                                           mHostID, mUserID, mUserType, mRoomType,
                                                           VideoActivity.this);
                mLvMember.setAdapter(mSortMemberAdapter);
            } else {
                mSortMemberAdapter.updateListView(mSourceDateList);
                mSortMemberAdapter.notifyDataSetChanged();
            }
            mSortMemberAdapter.mAnchorID = mAnchorID;

            filterData(mClearEditText.getText().toString().trim());
        }
    }

    /*举手的点击*/
    private void processRaiseHandClick() {
        if (!mImageRaiseHand.isSelected()) {
            mImageRaiseHand.setImageDrawable(ContextCompat.getDrawable(
                    getApplicationContext(), R.drawable.ic_menu_raise_hand_check));
            mImageRaiseHand.setSelected(true);
            ThreadUtils.runOnSubThread(new Runnable() {
                @Override
                public void run() {
                    SendRaiseHandMessge.sendMessge(true, mUserAcount, mUserID, egine, mGroup);
                }
            });
            Toast.makeText(VideoActivity.this, "举手", Toast.LENGTH_SHORT).show();
        } else {
            mImageRaiseHand.setImageDrawable(ContextCompat.getDrawable(
                    getApplicationContext(), R.drawable.ic_menu_raise_hand));
            mImageRaiseHand.setSelected(false);
            ThreadUtils.runOnSubThread(new Runnable() {
                @Override
                public void run() {
                    SendRaiseHandMessge.sendMessge(false, mUserAcount, mUserID, egine, mGroup);
                }
            });
            Toast.makeText(VideoActivity.this, "取消举手", Toast.LENGTH_SHORT).show();
        }
    }

    /*主播视频窗的点击*/
    private void processRemoteVideoContainerClick() {
        mVideofullscreenflag = !mVideofullscreenflag;

        LayoutParams layoutParams = mLlRemoteVideoContainer.getLayoutParams();
        LayoutParams leftParams = mLlView.getLayoutParams();
        if (mVideofullscreenflag) {
            ll_whiteboard.setVisibility(View.GONE);
            ll_divide.setVisibility(View.GONE);
            ll_below_video.setVisibility(View.GONE);
            mRlVideoIndicator.setVisibility(View.GONE);
            mLlLocalVideoContainer.setVisibility(View.GONE);
            mFlLocalVideoViewContainer.setVisibility(View.GONE);

            layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT;
            layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT;
            leftParams.width = LinearLayout.LayoutParams.MATCH_PARENT;
        } else {
            ll_whiteboard.setVisibility(View.VISIBLE);
            ll_divide.setVisibility(View.VISIBLE);
            ll_below_video.setVisibility(View.VISIBLE);
            mRlVideoIndicator.setVisibility(mRoomType == 3 ? View.GONE : View.VISIBLE);
            mLlLocalVideoContainer.setVisibility(mRoomType == 3 ? View.GONE : View.VISIBLE);
            mFlLocalVideoViewContainer.setVisibility(mRoomType == 3 ? View.GONE : View.VISIBLE);

            layoutParams.height = (int) (mRemoteVideoContainerWidth * 3.0 / 4.0);
            layoutParams.width = mRemoteVideoContainerWidth;
            leftParams.width = mRemoteVideoContainerWidth;
        }
        mLlView.setLayoutParams(leftParams);
        mLlView.invalidate();

        mLlRemoteVideoContainer.setLayoutParams(layoutParams);
        mLlRemoteVideoContainer.invalidate();
    }

    /*音乐播放或暂停的点击*/
    private void processMusicPlayPauseClick() {
        IsPlaying = !IsPlaying;
        mIvMusicPlayOrPause.setImageResource(IsPlaying ? R.drawable.selector_music_pause : R.drawable.selector_music_play);

        String mp3Name = SharedPreferencesUtils.getParam(VideoActivity.this, mFileID + "", "").toString();
        String mp3Path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/download/" + mp3Name + ".mp3";

        int time = 0;

        if (!TextUtils.isEmpty(mMusicCurrentPositionTime) && mMusicCurrentPositionTime != null) {
            time = Integer.parseInt(mMusicCurrentPositionTime);
        }

        if (IsPlaying) {
            musicPlay(mp3Path, time);
            SendMusicCommandMessage.sendMessge(time, mFileID, "play", mGroup);
        }else{
            musicPause(mp3Path);
            SendMusicCommandMessage.sendMessge(0, mFileID, "pause", mGroup);
        }
    }

    /*音乐停止的点击*/
    private void processMusicStopClick() {
        IsPlaying = false;

        String mp3Name = SharedPreferencesUtils.getParam(VideoActivity.this, mFileID + "", "").toString();
        String mp3Path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/download/" + mp3Name + ".mp3";

        musicStop(mp3Path);
        SendMusicCommandMessage.sendMessge(0, mFileID, "stop", mGroup);
        mMusicCurrentPositionTime = "0";
    }

    /*向导关闭的点击*/
    private void processGuideCloseClick() {
        mLlGuideView.setVisibility(View.GONE);
        SharedPreferencesUtils.setParam(this, Constant.ENTER_CLASSROOM_GUIDE, true);
    }

    /*emoji的点击*/
    private void processChatIconClick() {
        final String[] emojiStrs = getResources().getStringArray(R.array.emoji);

        mEmojiData = getEmojiData(30);

        final Dialog emojiDialog = new Dialog(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_emoji, null);
        emojiDialog.setContentView(view);

        Window dialogWindow = emojiDialog.getWindow();
        WindowManager.LayoutParams layoutParams = dialogWindow.getAttributes();
        layoutParams.height = (int) ((2.5 / 4.0) * mScreenHeight);
        layoutParams.width = LayoutParams.WRAP_CONTENT;
        dialogWindow.setAttributes(layoutParams);

        GridView gvEmoji = (GridView) view.findViewById(R.id.gv_emoji);
        gvEmoji.setAdapter(new EmojiAdapter(this, mEmojiData));
        gvEmoji.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                int argnum = position + 1;

                Drawable drawable = getResources().getDrawable((Integer) mEmojiData.get(position).get("image"));
                drawable.setBounds(0, 0, DensityUtil.dip2px(VideoActivity.this, 20), DensityUtil.dip2px(VideoActivity.this, 20));
                ImageSpan imageSpan = new ImageSpan(drawable);
                String strface;
                if (argnum < 10) {
                    strface = "</00" + argnum;
                } else {
                    strface = "</0" + argnum;
                }
                SpannableString spannableString = new SpannableString(strface + "/>");
                spannableString.setSpan(imageSpan, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                mEtBody.append(spannableString);
                mEtBody.setSelection(mEtBody.length());

                emojiDialog.dismiss();

            }
        });

        gvEmoji.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
            {
                if (mPopupWindow != null) {
                    mPopupWindow.dismiss();
                    mPopupWindow = null;
                }

                TextView textView = new TextView(VideoActivity.this);
                textView.setText(emojiStrs[position]);
                textView.setTextSize(DensityUtil.sp2px(VideoActivity.this, 3));
                mPopupWindow = new PopupWindow(textView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                mPopupWindow.showAsDropDown(view, DensityUtil.dip2px(VideoActivity.this, 33), - DensityUtil.dip2px(VideoActivity.this, 36));
                return true;
            }
        });
        emojiDialog.show();
        emojiDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (mPopupWindow != null) {
                    mPopupWindow.dismiss();
                    mPopupWindow = null;
                }
            }
        });
    }

    private List<Map<String, Object>> getEmojiData(int num) {
        List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
        int[] imageIds = new int[num + 1];
        for (int i = 1; i < num + 1; i++) {
            try {
                if (i < 10) {
                    Field field = R.drawable.class.getDeclaredField("f00" + i);
                    int resourceId = Integer.parseInt(field.get(null).toString());
                    imageIds[i] = resourceId;
                } else if (i < 100) {
                    Field field = R.drawable.class.getDeclaredField("f0" + i);
                    int resourceId = Integer.parseInt(field.get(null).toString());
                    imageIds[i] = resourceId;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            Map<String, Object> listItem = new HashMap<String, Object>();
            listItem.put("image", imageIds[i]);
            listItems.add(listItem);
        }
        return listItems;
    }

    /*发送的点击*/
    private void processSendClick() {
        if (isLimitTalk && mUserType != 4) {

            Message msg = Message.obtain();
            msg.what = ISLIMITTALK;
            mClockHandler.sendMessage(msg);
            return;
        }

        //巡视员角色不能发送信息
        if (mUserType == 4 && isInspectorFirstSendMsg) {
            View view = LayoutInflater.from(VideoActivity.this).inflate(R.layout.dialog_inspector_send_msg, null);

            TextView tvTipSure = (TextView) view.findViewById(R.id.tv_tip_sure);
            TextView tvTipCancel = (TextView) view.findViewById(R.id.tv_tip_cancel);

            tvTipSure.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    isInspectorFirstSendMsg = false;
                    mInspectorSendMsgDialog.dismiss();
                    processSendChatMsg();
                }
            });
            tvTipCancel.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    isInspectorFirstSendMsg = true;
                    mInspectorSendMsgDialog.dismiss();
                    return;
                }
            });

            AlertDialog.Builder builder = new AlertDialog.Builder(VideoActivity.this)
                    .setView(view);
            mInspectorSendMsgDialog = builder.show();
            mInspectorSendMsgDialog.setCanceledOnTouchOutside(false);
            mInspectorSendMsgDialog.setCancelable(false);
            mInspectorSendMsgDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)
                {
                    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                        return true;
                    }

                    return false;
                }
            });
        } else {
            processSendChatMsg();
        }
    }

    /*页码的点击*/
    public void processPageClick(){
        View view = LayoutInflater.from(VideoActivity.this).inflate(R.layout.dialog_input_page, null);

        final EditText edtPage = (EditText) view.findViewById(R.id.edt_page);
        TextView tvInputSure = (TextView) view.findViewById(R.id.tv_input_sure);
        TextView tvInputCancel = (TextView) view.findViewById(R.id.tv_input_cancel);

        tvInputSure.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mTurnPage = true;
                String input = edtPage.getText().toString().trim();
                if (!TextUtils.isEmpty(input)) {
                    int page = Integer.parseInt(input);

                    if (page >= 1 && page <= mPageNums) {
                        currentPage = page;
                        mArrowLeft.setVisibility(currentPage == 1 ? View.GONE : View.VISIBLE);
                        mArrowRight.setVisibility(currentPage == mPageNums ? View.GONE : View.VISIBLE);

                        if (isWebMode) {
                            webJump(currentPage);
                        } else {
                            imageurl = Constant.getDocUrl() + fileDir + "/" + currentPage + ".jpg";
                            LogUtil.i(TAG, "→自己手动翻页地址  " + imageurl);
                            loadImageBitmap(imageurl);
                            if (mUserType == 1 || mAnchor) {
                                upLoadCurrentTextBook(fileDir, currentPage);
                            }
                        }
                    }else if (page > mPageNums) {
                        Toast.makeText(VideoActivity.this, R.string.course_detail_page_over_num, Toast.LENGTH_SHORT).show();
                    }else if (page < 1) {
                        Toast.makeText(VideoActivity.this, R.string.course_detail_page_less_num, Toast.LENGTH_SHORT).show();
                    }
                }

                mInputPageDialog.dismiss();
            }
        });
        tvInputCancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mInputPageDialog.dismiss();
                return;
            }
        });

        AlertDialog.Builder builder = new AlertDialog.Builder(VideoActivity.this) .setView(view);
        mInputPageDialog = builder.show();
        mInputPageDialog.setCanceledOnTouchOutside(true);
        mInputPageDialog.setCancelable(true);
    }

    public class WifiChangeBroadcastReceiver extends BroadcastReceiver {
        private Context mContext;

        @Override
        public void onReceive(Context context, Intent intent) {
            mContext = context;
            LogUtil.e(TAG, "Wifi发生变化");
            int netWorkType = getNetWorkType(VideoActivity.this);
            switch (netWorkType) {
                case NETWORKTYPE_WIFI:
                    getWifiInfo();

                    if (egine == null && mUserID != 0 && !TextUtils.isEmpty(mUserName) && 0 != mUserType  && registerTag==false && cutNet==true){
                        registerTag = true;
                        cutNet =false;
                        isIMReconnect = true;

                        new Thread(new Runnable() {
                            @Override
                            public void run() {

                                doRegister(mUserID, mUserName, mUserType);
                            }
                        }).start();

                        String url = Constant.getDocUrl() + fileDir + "/" + currentPage + ".jpg";
                        loadImageBitmap(url);
                    }

                    break;
                case NETWORKTYPE_MOBILE:
                    Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_net_not_wifi), Toast.LENGTH_SHORT).show();

                    if (egine == null && mUserID != 0 && !TextUtils.isEmpty(mUserName) && 0 != mUserType && registerTag==false && cutNet==true){
                        registerTag = true;
                        cutNet =false;
                        isIMReconnect = true;

                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                doRegister(mUserID, mUserName, mUserType);
                            }
                        }).start();

                        String url = Constant.getDocUrl() + fileDir + "/" + currentPage + ".jpg";
                        loadImageBitmap(url);
                    }
                    break;
                case NETWORKTYPE_NONE:
                    cutNet=true;
                    isIMReconnect = false;
                    Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_net_cannot_use), Toast.LENGTH_SHORT).show();

                    if (egine != null){
                        ThreadUtils.runOnSubThread(new Runnable() {
                            @Override
                            public void run() {
                                //egine.LeaveGroup(mGroup);
                                egine.UnRegister();
                                egine = null;
                            }
                        });
                    }

                    registerTag =false;
                    break;
            }
        }

        public int getNetWorkType(Context context) {
            int mNetWorkType = -1;
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = manager.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isConnected()) {
                String type = networkInfo.getTypeName();
                if (type.equalsIgnoreCase("WIFI")) {
                    mNetWorkType = NETWORKTYPE_WIFI;
                } else if (type.equalsIgnoreCase("MOBILE")) {
                    return NETWORKTYPE_MOBILE;
                }
            } else {
                mNetWorkType = NETWORKTYPE_NONE;
            }
            return mNetWorkType;
        }

        private void getWifiInfo() {
            WifiManager wifiManager = (WifiManager) mContext.getSystemService(mContext.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            if (wifiInfo.getBSSID() != null) {
                //wifi名称
                String ssid = wifiInfo.getSSID();
                //wifi信号强度
                int signalLevel = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), 5);
                //wifi速度
                int speed = wifiInfo.getLinkSpeed();
                //wifi速度单位
                String units = WifiInfo.LINK_SPEED_UNITS;
                LogUtil.e("---", "ssid=" + ssid + ",signalLevel=" + signalLevel + ",speed=" + speed + ",units=" + units);

                long currentTimeMillis = System.currentTimeMillis();
                if (signalLevel < 3 && (currentTimeMillis - mShowWifiMsgTime) > (60 * 1000)) {
                    mShowWifiMsgTime = currentTimeMillis;
                    Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_net_not_great), Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    //IM断线重连后的命令发送
    private void doReconnectIM() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                ReconnectIMBean reconnectIMBean = new ReconnectIMBean();
                ReconnectIMBean.MessageBean messageBean = new ReconnectIMBean.MessageBean();
                messageBean.setType("reconnect");
                messageBean.setUserid(mUserID);
                messageBean.setUseracount(mUserAcount);
                reconnectIMBean.setMessage(messageBean);
                String msg = mGson.toJson(reconnectIMBean);
                LogUtil.e("reconnect", msg);
                FileLogUtils.write("IM Reconnect:" + msg);
                if (egine != null) {
                    egine.SendGroupMessage(Constant.CONTROLMSGTYPE, mGroup, msg);
                }
            }
        }).start();
    }

    /**
     * 注册当音量发生变化时接收的广播
     */
    private void registerVolumeChangeReceiver() {
        mVolumeReceiver = new VolumeChangeVolumeReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.media.VOLUME_CHANGED_ACTION");
        registerReceiver(mVolumeReceiver, filter);
    }

    /**
     * 音量变化时的处理
     * @author long
     */
    private class VolumeChangeVolumeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("android.media.VOLUME_CHANGED_ACTION") && rtcEngine != null) {
                int currVolume = am.getStreamVolume(AudioManager.STREAM_SYSTEM);
                int streamMaxVolume = am.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);
                if (currVolume == 0) {
                    //静音
                    rtcEngine.muteAllRemoteAudioStreams(true);
                } else {
                    rtcEngine.muteAllRemoteAudioStreams(false);
                    rtcEngine.setSpeakerphoneVolume(currVolume * (255 / streamMaxVolume));
                }
            }
        }
    }

    //点赞部分
    @Override
    public void setLike(String userId) {
        for (MemberItemInfo memberItemInfo : userlist) {
            if(memberItemInfo.getUserid().equals(userId)){
                memberItemInfo.setLikenum(memberItemInfo.getLikenum() + 1);
            }
        }

        if (userlist != null) {
            mSourceDateList = SortUtils.filledData(mCharacterParser, userlist);
            // 根据a-z进行排序源数据
            Collections.sort(mSourceDateList, mPinyinComparator);
        }

        if (mSortMemberAdapter == null) {
            mSortMemberAdapter = new SortMemberAdapter(VideoActivity.this, mSourceDateList, mHostID,mUserID,mUserType,mRoomType,this);
            mSortMemberAdapter.mAnchorID = mAnchorID;
        }
        ThreadUtils.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                mSortMemberAdapter.updateListView(mSourceDateList);
            }
        });

        Map<String, Object> zandata = new HashMap<String, Object>();
        zandata.put("actoruseracount",strAccount);
        zandata.put("actoruserid",mUserID);
        zandata.put("subcommand","like");
        zandata.put("type" ,"member");
        zandata.put("useracount",hostAccount);
        zandata.put("userid" ,Integer.parseInt(userId));
        JSONObject bodystr = new JSONObject(zandata);
        Map<String, Object> zandata1 = new HashMap<String, Object>();
        zandata1.put("message",zandata);
        LogUtil.i("like", "老师被点赞-----------zandata"+zandata.toString());
        final JSONObject zanobject = new JSONObject(zandata1);
        ThreadUtils.runOnSubThread(new Runnable() {
            @Override
            public void run() {
                if (egine != null) {
                    egine.SendGroupMessage(Constant.CONTROLMSGTYPE, mGroup, zanobject.toString());
                }
            }
        });
    }

    @Override
    public void onMenuClick(final String userId, final int userType) {
        mOperatedUserId = userId;
        final String[] answerStrs = new String[5];
        int itemCounts = 0;
        for (int i = 0; i < mOperationMenuBeanList.size(); i++) {
            if (mOperationMenuBeanList.get(i).getUseId().equals(userId))
            {
                boolean lockStatus = mOperationMenuBeanList.get(i).isLockStatus();
                boolean speakStatus = mOperationMenuBeanList.get(i).isSpeakStatus();
                boolean micStatus = mOperationMenuBeanList.get(i).isMicStatus();
                boolean videoStatus = mOperationMenuBeanList.get(i).isVideoStatus();
                if (mRoomType == 2) {
                    answerStrs[0] = lockStatus ? getResources().getString(R.string.course_detail_opretion_menu_unlock) : getResources().getString(R.string.course_detail_opretion_menu_lock);
                    answerStrs[1] = speakStatus ? getResources().getString(R.string.course_detail_opretion_menu_limit_talk) : getResources().getString(R.string.course_detail_opretion_menu_allow_talk);
                    answerStrs[2] = getResources().getString(R.string.course_detail_opretion_menu_goout);
                    answerStrs[3] = micStatus ? getResources().getString(R.string.course_detail_opretion_menu_close_audio) : getResources().getString(R.string.course_detail_opretion_menu_open_audio);
                    answerStrs[4] = videoStatus ? getResources().getString(R.string.course_detail_opretion_menu_close_video) : getResources().getString(R.string.course_detail_opretion_menu_open_video);
                    itemCounts = 5;
                } else if (mRoomType == 3) {
                    answerStrs[0] = getResources().getString(R.string.course_detail_opretion_menu_change_host);
                    if (Integer.parseInt(userId) == mHostID || userType == 3) {
                        itemCounts = 1;
                    } else {
                        answerStrs[1] = speakStatus ? getResources().getString(R.string.course_detail_opretion_menu_limit_talk) : getResources().getString(
                                R.string.course_detail_opretion_menu_allow_talk);
                        answerStrs[2] = getResources().getString(R.string.course_detail_opretion_menu_goout);
                        itemCounts = 3;
                    }
                }
            }
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(VideoActivity.this);

        View view = View.inflate(VideoActivity.this, R.layout.dialog_operation_menu, null);
        ListView listView = (ListView) view.findViewById(R.id.listView);
        final OperationMenuAdapter menuAdapter =  new OperationMenuAdapter(VideoActivity.this, answerStrs, itemCounts);
        listView.setAdapter(menuAdapter);

        builder.setView(view);
        mOperationMenuDialog = builder.create();
        mOperationMenuDialog.show();
        isOperationMenuDialog = true;
        WindowManager.LayoutParams params = mOperationMenuDialog.getWindow().getAttributes();
        params.width = DensityUtil.dip2px(VideoActivity.this, 300);
        mOperationMenuDialog.getWindow().setAttributes(params);

        mOperationMenuDialog.setCancelable(true);
        mOperationMenuDialog.setCanceledOnTouchOutside(true);

        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                for (int i = 0; i < mOperationMenuBeanList.size(); i++) {
                    if (mOperationMenuBeanList.get(i).getUseId().equals(userId))
                    {

                        if (position == 0) {
                            if (mRoomType == 2) {
                                boolean lockStatus = mOperationMenuBeanList.get(i).isLockStatus();
                                mOperationMenuBeanList.get(i).setLockStatus(!lockStatus);
                                unLockUser(lockStatus, Integer.parseInt(userId));
                            } else if (mRoomType == 3) {
                                changeHost("changehost", Integer.parseInt(userId), userType);
                            }
                        } else if (position == 1) {
                            boolean speakStatus = mOperationMenuBeanList.get(i).isSpeakStatus();
                            mOperationMenuBeanList.get(i).setSpeakStatus(!speakStatus);

                            limitSpeak(speakStatus, Integer.parseInt(userId));
                        } else if (position == 2) {
                            eliminate("goout", Integer.parseInt(userId));
                        }else if (position == 3) {
                            boolean micStatus = mOperationMenuBeanList.get(i).isMicStatus();
                            mOperationMenuBeanList.get(i).setMicStatus(!micStatus);

                            micVideoControl("mic", micStatus, Integer.parseInt(userId));
                        }else if (position == 4) {
                            boolean videoStatus = mOperationMenuBeanList.get(i).isVideoStatus();
                            mOperationMenuBeanList.get(i).setVideoStatus(!videoStatus);

                            micVideoControl("camera", videoStatus, Integer.parseInt(userId));
                        }

                        mOperationMenuDialog.dismiss();
                        isOperationMenuDialog = false;
                    }
                }
            }
        });
    }

    /**
     * 发送切换主讲的命令
     * @param command
     * @param userId
     */
    private void changeHost(String command, int userId, int userType) {
        SendControlCommandMessage.sendMessge(command, userId, mHostID, mGroup);
        mAnchorID = userId;
        mSortMemberAdapter.mAnchorID = userId;
        mSortMemberAdapter.notifyDataSetChanged();

        if (mUserID == userId) {
            rtcEngine.leaveChannel();
            rtcEngine.joinChannel(channelkey, mRoomID + "", "", mUserID);
            rtcEngine.setClientRole(1, "");
            mAnchor = true;
            setupLocalVideo(mFlRemoteVideoViewContainer);
        } else {
            setupRemoteVideo(userId);
            rtcEngine.muteLocalVideoStream(true);
        }
    }

    private void micVideoControl(String command, boolean toggle , int userId){
        String flag = toggle ? "off" : "on";
        SendMicVideoMessage.sendMessge(command, flag, userId, mGroup);

        if (command.equals("camera")) {
            if (toggle) {
                for (int j = 0; j < mUserIdLists.size(); j++) {
                    if (mUserIdLists.get(j).equals(userId + "")) {
                        mUserIdLists.remove(j);
                        if (mCurrentMultiVideoNum >= j) {
                            mCurrentMultiVideoNum--;
                        }
                    }
                }
            } else {
                mUserIdLists.add(userId + "");
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if ((mRoomType != 3) && (mUserID == mHostID || mUserType == 3)) {
                        if (mUserIdLists.size() > 0) {
                            mCurrentMultiVideoNum = mCurrentMultiVideoNum < 0 ? 0 : mCurrentMultiVideoNum;
                            setupVideoStream(Integer.parseInt(mUserIdLists.get(mCurrentMultiVideoNum)), mFlLocalVideoViewContainer);
                        }else {
                            mFlLocalVideoViewContainer.removeAllViews();
                            mLlLocalVideoContainer.setBackgroundResource(R.drawable.defautteacherimage);
                        }
                        drawIndicator(mCurrentMultiVideoNum, mUserIdLists.size());
                    }
                }
            });
        }
    }

    /**
     * 发送踢人的命令
     * @param command
     * @param userId
     */
    private void eliminate(final String command, final int userId) {

        AlertDialog.Builder builder = new AlertDialog.Builder(VideoActivity.this)
                .setTitle(getResources().getString(R.string.course_tip))
                .setMessage(getResources().getString(R.string.course_detail_whether_eliminate_user))
                .setIcon(android.R.drawable.ic_dialog_info)
                .setPositiveButton(getResources().getString(R.string.course_sure), new DialogInterface.OnClickListener() {

                       @Override
                       public void onClick(DialogInterface dialog, int which) {
                           SendControlCommandMessage.sendMessge(command, userId, mHostID, mGroup);

                           for (int i = 0; i < userlist.size(); i++) {
                               if (userlist.get(i).getUserid().equals(userId + "")) {
                                   userlist.remove(i);
                               }
                           }
                           for (int j = 0; j < mUserIdLists.size(); j++) {
                               if (mUserIdLists.get(j).equals(userId + "")) {
                                   mUserIdLists.remove(j);
                                   if (mCurrentMultiVideoNum >= j) {
                                       mCurrentMultiVideoNum--;
                                   }
                               }
                           }
                           runOnUiThread(new Runnable() {
                               @Override
                               public void run() {
                                   if (mSortMemberAdapter != null) {
                                       mSourceDateList = SortUtils.filledData(mCharacterParser, userlist);
                                       Collections.sort(mSourceDateList, mPinyinComparator);
                                       mSortMemberAdapter.updateListView(mSourceDateList);
                                   }

                                   if ((mRoomType != 3) && (mUserID == mHostID || mUserType == 3)) {
                                       if (mUserIdLists.size() > 0) {
                                           mCurrentMultiVideoNum = mCurrentMultiVideoNum < 0 ? 0 : mCurrentMultiVideoNum;
                                           setupVideoStream(Integer.parseInt(mUserIdLists.get(mCurrentMultiVideoNum)), mFlLocalVideoViewContainer);
                                       }else {
                                           mFlLocalVideoViewContainer.removeAllViews();
                                           mLlLocalVideoContainer.setBackgroundResource(R.drawable.defautteacherimage);
                                       }
                                       drawIndicator(mCurrentMultiVideoNum, mUserIdLists.size());
                                   }
                               }
                           });
                   }
               })
               .setNegativeButton(getResources().getString(R.string.course_cancel), new DialogInterface.OnClickListener() {
                   @Override
                   public void onClick(DialogInterface dialog, int which) {
                       // 点击“返回”后的操作,这里不设置没有任何操作
                       dialog.dismiss();
                   }
               });
        AlertDialog alertDialog = builder.show();
        alertDialog.setCancelable(true);
        alertDialog.setCanceledOnTouchOutside(true);
    }

    /**
     * 发送禁言的命令
     * @param speakStatus
     * @param userId
     */
    private void limitSpeak(boolean speakStatus, int userId) {
        SendSpeakControlMessage.sendMessge(speakStatus, userId, mHostID, mGroup);
    }

    private void initListener() {
        mRlDialogue.setOnClickListener(this);
        mRlMember.setOnClickListener(this);
        mLlRemoteVideoContainer.setOnClickListener(this);
        mImageRaiseHand.setOnClickListener(this);
        mIvMusicPlayOrPause.setOnClickListener(this);
        mIvMusicStop.setOnClickListener(this);
        mIvGuideClose.setOnClickListener(this);
        mIvEmoji.setOnClickListener(this);
        mBtnSend.setOnClickListener(this);
        mPageText.setOnClickListener(this);
        mRlMusic.setOnClickListener(this);

        mArrowLeft.setOnClickListener(this);
        mArrowRight.setOnClickListener(this);

        mLlLocalVideoContainer.setOnTouchListener(new View.OnTouchListener() {
            float downX;
            float downY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        downX = event.getX();
                        downY = event.getY();

                        long currentTimeMillis = System.currentTimeMillis();

                        isMultiVideoSwitch = false;
                        if (currentTimeMillis - mClickLastTime > 200) {
                            mClickLastTime = currentTimeMillis;
                        } else {
                            multiVideoWindowsChange();
                        }

                        break;

                    case MotionEvent.ACTION_MOVE:
                        float moveX = event.getX();
                        float moveY = event.getY();

                        if (downX - moveX > 50) {
                            isMultiVideoSwitch = true;
                            mClickLastTime = 0;
                        } else if(moveX - downX > 50) {
                            isMultiVideoSwitch = true;
                            mClickLastTime = 0;
                        } else if(Math.abs(moveX - downX) < 50 || Math.abs(moveY - downY) < 50 ){
                            isMultiVideoSwitch = false;
                        }

                        break;

                    case MotionEvent.ACTION_UP:
                        if (isMultiVideoSwitch && mRoomType == 2) {
                            if(event.getX() - downX < 0){
                                mCurrentMultiVideoNum++;
                            } else if (event.getX() - downX > 0) {
                                mCurrentMultiVideoNum--;
                            }

                            if (mCurrentMultiVideoNum >= mUserIdLists.size()) {
                                mCurrentMultiVideoNum = mUserIdLists.size() - 1;
                                Toast.makeText(VideoActivity.this, "后面没有了", Toast.LENGTH_SHORT).show();
                            }else if(mCurrentMultiVideoNum >= 0){
                                if (mUserType == 2 && mCurrentMultiVideoNum == 0) {
                                    setupLocalVideo(mFlLocalVideoViewContainer);
                                }else{
                                    String currentMultiVideoUserId = mUserIdLists.get(mCurrentMultiVideoNum);
                                    setupVideoStream(Integer.parseInt(currentMultiVideoUserId), mFlLocalVideoViewContainer);
                                }
                            }else{
                                mCurrentMultiVideoNum = 0;
                                Toast.makeText(VideoActivity.this, "前面没有了", Toast.LENGTH_SHORT).show();
                            }

                            drawIndicator(mCurrentMultiVideoNum, mUserIdLists.size());
                        }

                        break;
                }
                return true;
            }
        });

        if (isTabDevice()) {
            //平板设备
            //常用语
            mIvCommonWord.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    showQuickAnswerDialog();
                }
            });
            //计时
            mTimerView.setTimerListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (userlist != null && mUserID == mHostID) {
                        if (userlist.size() > 1) {
                            if (mRoomType == 3) {
                                //大班课，教师计时开启录像
                                startRecording();
                            }
                            if (mRoomType != 1 && !isTimeStart) {
                                mTimerView.setToggleTimeCount(true);

                                isTimeStart = true;

                                ClockBean clockBean = new ClockBean();
                                clockBean.setType("timer");
                                clockBean.setSubcommand("start");

                                SendClockMessage.sendMessge(mGroup, 0);

                                setTimerDate(clockBean);
                            }
                        } else {
                            Toast.makeText(VideoActivity.this, "课堂中没有学生，暂不能开启计时", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            });
            //刷新
            mBtnWbRefresh.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    processRefresh();
                }
            });
            mBtnWbRemarks.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    processRemarks();
                }
            });

        } else {
            mEtBody.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    showQuickAnswerDialog();
                    return true;
                }
            });
        }

        //根据输入框输入值的改变来过滤搜索
        mClearEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        mEtBody.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mEtBody.setFocusable(true);
                mEtBody.setFocusableInTouchMode(true);
                mEtBody.requestFocus();
                getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
            }
        });

        mEtBody.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

                    return true;
                }

                return false;
            }
        });

        mTimerView.setQuitListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //弹出对话框询问是否退出频道
                new AlertDialog.Builder(VideoActivity.this).setTitle(getResources().getString(R.string.course_tip))
                        .setMessage(getResources().getString(R.string.course_whether_exit_app))
                        .setIcon(android.R.drawable.ic_dialog_info)
                        .setPositiveButton(getResources().getString(R.string.course_sure), new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 点击“确认”后的操作
                                ThreadUtils.runOnSubThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (egine != null) {
                                            egine.LeaveGroup(mGroup);
                                            egine.UnRegister();
                                            egine = null;
                                        }
                                    }
                                });

                                if (mUserID == mHostID) {
                                    stopRecording();
                                }

                                if (rtcEngine != null) {
                                    rtcEngine.leaveChannel();
                                }

                                finish();

                                if (isVoucherJump) {
                                    System.exit(0);
                                }
                            }
                        })
                        .setNegativeButton(getResources().getString(R.string.course_cancel), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 点击“返回”后的操作,这里不设置没有任何操作
                                dialog.dismiss();
                            }
                        }).show();
            }
        });
        mTimerView.setSettingsListener(new OnClickListener() {
            @Override
            public void onClick(View view) {

                processSettings();
            }
        });
    }

    private void processRemarks() {
        //备注处理
        isRemarksShow = !isRemarksShow;
        mFlRemarks.setVisibility(isRemarksShow
                                 ? View.VISIBLE : View.GONE);
        if (isRemarksShow) {
            if (isWebMode) {
                //TODO web备注
            } else {
                mTvRemarksContent.setText(mRoomRemarks);
            }
        }
    }

    private void processRefresh() {
        //刷新处理

        if (isWebMode) {
            mWebView.post(new Runnable() {
                @Override
                public void run() {
                    mWebView.loadUrl("javascript::Presentation.LoadPres(\"pres\"," + currentPage + ");");
                }
            });
        }else {
            final String imgUrl = Constant.getDocUrl() + fileDir + "/" + currentPage + "" + ".jpg";;
            LogUtil.e("refresh_url", imgUrl);

            if (mGraffitiView.mPathStackBackup.size() > 0)
            {
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle("Tips");
                builder.setMessage(getResources().getString(R.string.course_whiteboard_refresh_tip));
                builder.setPositiveButton("Sure", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mGraffitiView.clearService();
                        loadImageBitmap(imgUrl);
                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
                AlertDialog alertDialog = builder.show();
                alertDialog.setCancelable(true);
                alertDialog.setCanceledOnTouchOutside(true);
            } else {
                mGraffitiView.clearService();
                loadImageBitmap(imgUrl);
            }
        }
    }

    /**
     * 显示快速回复对话框
     */
    private void showQuickAnswerDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(VideoActivity.this);

        String[] answerStrs = getResources().getStringArray(R.array.quick_answers);

        View view = View.inflate(VideoActivity.this, R.layout.dialog_qucik_answer, null);
        ListView listView = (ListView) view.findViewById(R.id.listView);
        listView.setAdapter(new QucikAnswersAdapter(answerStrs));

        builder.setView(view);
        mQuickAnswersDialog = builder.create();
        mQuickAnswersDialog.show();
        WindowManager.LayoutParams params = mQuickAnswersDialog.getWindow()
                                                               .getAttributes();
        params.width = DensityUtil.dip2px(VideoActivity.this, 320);
        mQuickAnswersDialog.getWindow().setAttributes(params);

        mQuickAnswersDialog.setCancelable(true);
        mQuickAnswersDialog.setCanceledOnTouchOutside(true);
    }

    private void processSettings() {
        View view = View.inflate(this, R.layout.dialog_settings, null);
        LinearLayout llAudioVideoSwitch = (LinearLayout) view.findViewById(R.id.ll_audio_video_switch);
        LinearLayout llCameraSwitch = (LinearLayout) view.findViewById(R.id.ll_camera_switch);
        RelativeLayout rlAccountLock = (RelativeLayout) view.findViewById(R.id.rl_account_lock);
        View viewAudioVideoSwitch = view.findViewById(R.id.view_audio_video_switch);
        View viewAccountLock = view.findViewById(R.id.view_account_lock);
        final ImageView ivVideo = (ImageView) view.findViewById(R.id.iv_video);
        final ImageView ivAudio = (ImageView) view.findViewById(R.id.iv_audio);
        final TextView tvFrontCamera = (TextView) view.findViewById(R.id.tv_front_camera);
        final TextView tvRearCamera = (TextView) view.findViewById(R.id.tv_rear_camera);
        final ImageView ivAccountLock = (ImageView) view.findViewById(R.id.iv_account_lock);
        TextView tvVersionInfo = (TextView) view.findViewById(R.id.tv_version_info);

        llAudioVideoSwitch.setVisibility(mUserID == mHostID ? View.VISIBLE : View.GONE);
        llCameraSwitch.setVisibility((mUserType == 3 || mUserType == 4) ? View.GONE : View.VISIBLE);
        viewAudioVideoSwitch.setVisibility(mUserID == mHostID ? View.VISIBLE : View.GONE);
        rlAccountLock.setVisibility(mUserID == mHostID ? View.VISIBLE : View.GONE);
        viewAccountLock.setVisibility(mUserID == mHostID ? View.VISIBLE : View.GONE);


        ivVideo.setImageResource(isVideoMode
                                 ? R.drawable.video_selected : R.drawable.video_normal);
        ivAudio.setImageResource(isVideoMode
                                 ? R.drawable.audio_normal : R.drawable.audio_selected);

        tvFrontCamera.setBackgroundResource(isFrontCamera
                                            ? R.drawable.shape_camera_bg_selected : R.drawable.shape_camera_bg_normal);
        tvRearCamera.setBackgroundResource(isFrontCamera
                                           ? R.drawable.shape_camera_bg_normal : R.drawable.shape_camera_bg_selected);
        ivAccountLock.setImageResource(isAccountLocked ? R.drawable.toggle_open_icon : R.drawable.toggle_close_icon);


        ivVideo.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isVideoMode) {
                    isVideoMode = true;
                    ivVideo.setImageResource(R.drawable.video_selected);
                    ivAudio.setImageResource(R.drawable.audio_normal);
                    switchToVideoMode();
                    SendMicVideoMessage.sendMessge("switchToVideo", "yes", 0, mGroup);
                }
            }
        });
        ivAudio.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isVideoMode) {
                    isVideoMode = false;
                    ivVideo.setImageResource(R.drawable.video_normal);
                    ivAudio.setImageResource(R.drawable.audio_selected);
                    switchToAudioMode();
                    SendMicVideoMessage.sendMessge("switchToAudio", "yes", 0, mGroup);
                }
            }
        });
        tvFrontCamera.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isFrontCamera) {
                    isFrontCamera = true;
                    tvFrontCamera.setBackgroundResource(R.drawable.shape_camera_bg_selected);
                    tvRearCamera.setBackgroundResource(R.drawable.shape_camera_bg_normal);
                    rtcEngine.switchCamera();
                }
            }
        });
        tvRearCamera.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isFrontCamera) {
                    isFrontCamera = false;
                    tvRearCamera.setBackgroundResource(R.drawable.shape_camera_bg_selected);
                    tvFrontCamera.setBackgroundResource(R.drawable.shape_camera_bg_normal);
                    rtcEngine.switchCamera();
                }
            }
        });
        ivAccountLock.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                isAccountLocked = !isAccountLocked;
                ivAccountLock.setImageResource(isAccountLocked ? R.drawable.toggle_open_icon : R.drawable.toggle_close_icon);
                ThreadUtils.runOnSubThread(new Runnable() {
                    @Override
                    public void run() {
                        egine.lockUserAccount(mUserID, isAccountLocked ? 1 : 0);
                    }
                });
            }
        });

        try {
            PackageManager pm = getPackageManager();
            PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
            String versionName = packageInfo.versionName;
            tvVersionInfo.setText(versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this).setView(view);

        android.support.v7.app.AlertDialog settingsDialog = builder.show();
        settingsDialog.setCancelable(true);
        settingsDialog.setCanceledOnTouchOutside(true);

        WindowManager.LayoutParams params = settingsDialog.getWindow().getAttributes();
        if (isTabDevice()) {
            params.width = mScreenWidth * 2 / 5;
        } else {
            params.width = mScreenWidth * 2 / 3;
        }
        settingsDialog.getWindow().setAttributes(params);
    }

    private void switchToVideoMode() {
        rtcEngine.muteLocalVideoStream(false);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_live_video), Toast.LENGTH_SHORT).show();

                if (mUserID == mHostID) {
                    setupLocalVideo(mFlRemoteVideoViewContainer);
                } else {
                    if (mRemoteStreamUid != 0) {
                        setupVideoStream(mRemoteStreamUid, mFlRemoteVideoViewContainer);
                    } else {
                        mFlRemoteVideoViewContainer.setBackgroundResource(R.drawable.defautteacherimage);
                    }
                }

                if (mUserType == 2 && mCurrentMultiVideoNum == 0) {
                    setupLocalVideo(mFlLocalVideoViewContainer);
                } else {
                    if (mUserIdLists.size() > 0) {
                        mCurrentMultiVideoNum = mCurrentMultiVideoNum < 0 ? 0 : mCurrentMultiVideoNum;
                        setupVideoStream(Integer.parseInt(mUserIdLists.get(mCurrentMultiVideoNum)), mFlLocalVideoViewContainer);
                    } else {
                        mFlLocalVideoViewContainer.removeAllViews();
                        mFlLocalVideoViewContainer.setBackgroundResource(R.drawable.defautteacherimage);
                    }
                }

                drawIndicator(mCurrentMultiVideoNum , mUserIdLists.size());
            }
        });
    }

    private void switchToAudioMode() {
        rtcEngine.muteLocalVideoStream(true);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_live_audio), Toast.LENGTH_SHORT).show();

                mFlRemoteVideoViewContainer.removeAllViews();
                mFlRemoteVideoViewContainer.setBackgroundResource(R.drawable.max_audio_background);

                mFlLocalVideoViewContainer.removeAllViews();
                mFlLocalVideoViewContainer.setBackgroundResource(R.drawable.max_audio_background);
            }
        });
    }

    private void multiVideoWindowsChange() {
        localMainViewFlag = !localMainViewFlag;

        LayoutParams layoutParams = mLlLocalVideoContainer.getLayoutParams();
        LayoutParams layoutParams1 = mRlVideoIndicator.getLayoutParams();
        LayoutParams leftParams = mLlView.getLayoutParams();

        if (localMainViewFlag) {
            ll_whiteboard.setVisibility(View.GONE);
            ll_divide.setVisibility(View.GONE);
            ll_below_video.setVisibility(View.GONE);
            mLlRemoteVideoContainer.setVisibility(View.GONE);

            layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT;
            layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT;
            layoutParams1.height = LinearLayout.LayoutParams.MATCH_PARENT;
            layoutParams1.width = LinearLayout.LayoutParams.MATCH_PARENT;
            leftParams.width = LinearLayout.LayoutParams.MATCH_PARENT;
        } else {
            ll_whiteboard.setVisibility(View.VISIBLE);
            ll_divide.setVisibility(View.VISIBLE);
            ll_below_video.setVisibility(View.VISIBLE);
            mLlRemoteVideoContainer.setVisibility(View.VISIBLE);

            layoutParams.height = mRemoteVideoContainerWidth * 3 / 4;
            layoutParams.width = mRemoteVideoContainerWidth;
            layoutParams1.height = mRemoteVideoContainerWidth * 3 / 4;
            layoutParams1.width = mRemoteVideoContainerWidth;
            leftParams.width = mRemoteVideoContainerWidth;
        }

        mLlView.setLayoutParams(leftParams);
        mLlView.invalidate();

        mLlLocalVideoContainer.setLayoutParams(layoutParams);
        mLlLocalVideoContainer.invalidate();

        mRlVideoIndicator.setLayoutParams(layoutParams1);
        mRlVideoIndicator.invalidate();
    }

    class QucikAnswersAdapter extends BaseAdapter {

        String[] strs;

        public QucikAnswersAdapter(String[] strs) {
            this.strs = strs;
        }

        @Override
        public int getCount() {
            return strs != null ? strs.length : 0;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            TextView textView = new TextView(VideoActivity.this);
            textView.setTextColor(Color.BLACK);
            textView.setPadding(DensityUtil.dip2px(VideoActivity.this, 3), 0, 0, 0);
            textView.setGravity(Gravity.CENTER_VERTICAL);
            textView.setText(strs[position]);
            textView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!cutNet) {
                        sendChatMsg(strs[position]);
                    } else {
                        Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_net_cannot_use), Toast.LENGTH_SHORT).show();
                    }
                    mQuickAnswersDialog.dismiss();
                }
            });
            return textView;
        }
    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<SortMemberBean> filterDateList = new ArrayList<SortMemberBean>();

        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = mSourceDateList;
        } else {
            filterDateList.clear();
            for (SortMemberBean sortModel : mSourceDateList) {
                String name = sortModel.getUsername();
                if (name.indexOf(filterStr.toString()) != -1 || mCharacterParser.getSelling(name).startsWith(filterStr.toString())) {
                    filterDateList.add(sortModel);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, mPinyinComparator);
        mSortMemberAdapter.updateListView(filterDateList);
        mSortMemberAdapter.notifyDataSetChanged();
    }

    /***
     * 网站app跳转eclass上课
     */
    private void browser2app(){

        try {
            sub = uri.toString().split("://")[1];
            byte[] result = Base64.decode(sub, Base64.DEFAULT);

            encode_eclass_json = new String(result, "utf-8");

            if (encode_eclass_json.contains("UserName")) {
                infoStr = encode_eclass_json;
            } else {
                infoStr = StringEncrypt.S1Decrypt(sub, Info.Protocol_EncryptionKey);
                //s-1协议解密
            }

            FileLogUtils.write("RoomInfo: " + infoStr);

            courseinfojson = new JSONObject(infoStr);

            long timestamp = courseinfojson.getLong("Timestamp");

            //校验协议时效性
            verifyConnectionTime("voucher", timestamp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void VaildAgreement(){

        try {
            if(!courseinfojson.getString("Command").equals("Run")) {

                mUserName = courseinfojson.getString("UserName");
                mUserType = courseinfojson.getInt("UserType");
                mUserID = courseinfojson.getInt("UserID");

                if (courseinfojson.has("RoomInfo")) {
                    JSONObject roomInfo = courseinfojson.getJSONObject("RoomInfo");

                    mHostID = roomInfo.getInt("HostID");
                    mAnchorID = mHostID;

                    mRoomType = roomInfo.getInt("RoomType");

                    mRoomID = roomInfo.getInt("RoomID");

                    roomName = roomInfo.getString("RoomName");

                    if (isVoucherJump) {
                        menu_5();
                    }

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            doRegister(mUserID, mUserName, mUserType);
                        }
                    }).start();
                }
                if (courseinfojson.has("FileInfo")) {
                    JSONArray jarray = courseinfojson.getJSONArray("FileInfo");
                    FileInfo_list = new ArrayList<FileInfo>();
                    //FileInfo_list = mGson.fromJson(jarray.toString(), new TypeToken<List<FileInfo>>(){}.getType());

                    for (int i = 0; i < jarray.length(); i++) {
                        JSONObject mFileInfo = jarray.getJSONObject(i);
                        FileInfo fileinfo = mGson.fromJson(mFileInfo.toString(), FileInfo.class);
                        FileInfo_list.add(fileinfo);
                        // 存FileInfo信息

                        mFileID = fileinfo.getFileID();
                        SharedPreferencesUtils.setParam(VideoActivity.this, fileinfo.getFileID() + "", fileinfo.getFileDir());
                        SharedPreferencesUtils.setParam(VideoActivity.this, fileinfo.getFileID()+"pagenum", Integer.parseInt(fileinfo.getPageNums()));
                        LogUtil.i(TAG, "存FileInfo信息: " + mFileID + "---" + FileInfo_list.get(i).getFileDir());
                    }
                    mp3list = new ArrayList<String>();
                    for (int i = 0; i < FileInfo_list.size(); i++) {
                        SharedPreferencesUtils.setParam(this, FileInfo_list.get(i).getFileID() + "", FileInfo_list.get(i).getFileDir());
                        if (FileInfo_list.get(i).getFileName().contains(".mp3") ||
                                FileInfo_list.get(i).getFileName().contains(".wav") ||
                                FileInfo_list.get(i).getFileName().contains(".wma")) {
                            mp3list.add(FileInfo_list.get(i).getFileID() + "");

                        }
                    }
                    // 通过获取到的数据，加载教材

                    fileDir = FileInfo_list.get(0).getFileDir();
                    mFileID = FileInfo_list.get(0).getFileID();
                    mPageNums = Integer.parseInt(FileInfo_list.get(0).getPageNums());
                    //拼接成第一个教材地址URL

                    mUrl1 = Constant.getDocUrl() + fileDir + "/" + "1.jpg";
                    LogUtil.i(TAG, "第一个教材地址URL: " + mUrl1);
                } else {
                    //mUrl1 = "http://120.77.155.192:8080/IdHYwoLGnCVXctW/1.jpg";
                    fileDir = fileDirWhiteBorad;
                    mFileID = 1;
                    currentPage = 1;
                    mPageNums = 10;
                    mUrl1 = Constant.getDocUrl() + fileDirWhiteBorad + "/" + currentPage +".jpg";
                }

                mCatalogLists = new ArrayList<>();
                if (FileInfo_list != null) {
                    for (int i= 0; i < FileInfo_list.size(); i++) {
                        String fileName = FileInfo_list.get(i).getFileName();
                        String fileDir = "IdHYwoLGnCVXctW";
                        if (fileName.contains(".mp3") || fileName.contains(".wav") || fileName.contains(
                                ".wma"))
                        {
                        } else {
                            fileDir = FileInfo_list.get(i).getFileDir();
                        }
                        String pageNums = FileInfo_list.get(i).getPageNums();
                        int fileId = FileInfo_list.get(i).getFileID();
                        CatalogBean catalogBean = new CatalogBean(fileName, fileDir, pageNums, 1,
                                                                  fileId);
                        catalogBean.setFileType("JPG");
                        mCatalogLists.add(catalogBean);
                    }
                }

                mH5List = new ArrayList<>();
                if (courseinfojson.has("HtmlFileInfo")) {
                    JSONArray htmlFileInfo = courseinfojson.getJSONArray("HtmlFileInfo");

                    for (int i = 0; i < htmlFileInfo.length(); i++) {
                        JSONObject jsonObject = htmlFileInfo.getJSONObject(i);
                        FileInfo fileInfo = mGson.fromJson(jsonObject.toString(), FileInfo.class);
                        mH5List.add(fileInfo);
                        FileInfo_list.add(fileInfo);
                        String filename = fileInfo.getFileName();
                        String filedir = fileInfo.getFileDir();
                        String pagenum = fileInfo.getPageNums();
                        int fileid = fileInfo.getFileID();
                        CatalogBean h5CatalogBean = new CatalogBean(filename, filedir, pagenum,
                                                                    1, fileid);
                        h5CatalogBean.setFileType("H5");
                        mCatalogLists.add(h5CatalogBean);
                    }
                }

                if (mH5List.size() > 0) {
                    startWebMode(true);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            OpenWebCommandBean.MessageBean messageBean = new OpenWebCommandBean.MessageBean();
                            OpenWebCommandBean.MessageBean.WhiteboardBean whiteboardBean = new OpenWebCommandBean.MessageBean.WhiteboardBean();

                            mFileID = mH5List.get(0).getFileID();
                            fileDir = mH5List.get(0).getFileDir();
                            whiteboardBean.setFilename(mH5List.get(0).getFileName());
                            whiteboardBean.setFiledir(mH5List.get(0).getFileDir());
                            whiteboardBean.setDocserver(Constant.getH5BASEURL());
                            whiteboardBean.setSubcommand("openweb");
                            whiteboardBean.setCurrentpage(1);
                            whiteboardBean.setCurrentaction(0);
                            whiteboardBean.setPagenum(0);
                            whiteboardBean.setFileid(mFileID);

                            messageBean.setType("whiteboard");
                            messageBean.setWhiteboard(whiteboardBean);
                            openWeb(messageBean);
                        }
                    });
                }

            }else{
                LogUtil.i("Test","短协议"); //TODO :
                String urlid = courseinfojson.getString("URLID");

                HttpUtils httpUtils = new HttpUtils();
                RequestParams params = new RequestParams();
                VerificationKeyUtils keyUtils = new VerificationKeyUtils();
                String verificationKey = keyUtils.getVerificationKey(Info.MECHANISM_ID);
                params.addBodyParameter("Version",Info.APIVERSION);
                params.addBodyParameter("URLID",urlid);
                params.addBodyParameter("VerificationKey",verificationKey);

                httpUtils.send(HttpRequest.HttpMethod.POST, Constant.getEnterRoomCommandUrl(), params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        try {
                            JSONObject jsonObject = new JSONObject(responseInfo.result);
                            String result1 = jsonObject.getString("Result");
                            if(result1.equals("true")){
                                String command = jsonObject.getString("Command");

                                //String substring = command.toString().substring(9);
                                String substring = command.toString().split("://")[1];
                                byte[] result = Base64.decode(substring, Base64.DEFAULT);

                                try {
                                    encode_eclass_json = new String(result, "utf-8");
                                    FileLogUtils.write("网站app跳转eclass 短协议上课 " + encode_eclass_json);

                                    if (encode_eclass_json.contains("UserName")) {
                                        infoStr = encode_eclass_json;
                                    } else {
                                        infoStr = StringEncrypt.S1Decrypt(sub, Info.Protocol_EncryptionKey);
                                        //s-1协议解密
                                    }

                                    courseinfojson = new JSONObject(infoStr);

                                    if(!courseinfojson.getString("Command").equals("Run")) {

                                        mUserName = courseinfojson.getString("UserName");
                                        mUserType = courseinfojson.getInt("UserType");
                                        mUserID = courseinfojson.getInt("UserID");

                                        if (courseinfojson.has("RoomInfo")) {
                                            JSONObject roomInfo = courseinfojson.getJSONObject("RoomInfo");

                                            mHostID = roomInfo.getInt("HostID");
                                            mAnchorID = mHostID;

                                            mRoomType = roomInfo.getInt("RoomType");

                                            mRoomID = roomInfo.getInt("RoomID");

                                            roomName = roomInfo.getString("RoomName");

                                            if (isVoucherJump) {
                                                menu_5();
                                            }

                                            new Thread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    doRegister(mUserID, mUserName, mUserType);
                                                }
                                            }).start();

                                        }
                                        if (courseinfojson.has("FileInfo")) {

                                            JSONArray jarray = courseinfojson.getJSONArray("FileInfo");
                                            FileInfo_list = new ArrayList<FileInfo>();
                                            for (int i = 0; i < jarray.length(); i++) {
                                                JSONObject mFileInfo = jarray.getJSONObject(i);
                                                FileInfo fileinfo = mGson.fromJson(mFileInfo.toString(), FileInfo.class);
                                                FileInfo_list.add(fileinfo);
                                                //存FileInfo信息

                                                SharedPreferencesUtils.setParam(VideoActivity.this, FileInfo_list.get(i).getFileID() + "", FileInfo_list.get(i).getFileDir());
                                                LogUtil.i(TAG, "存FileInfo信息: " + FileInfo_list.get(i).getFileID() + "---" + FileInfo_list.get(i).getFileDir());
                                            }
                                            mp3list = new ArrayList<String>();
                                            for (int i = 0; i < FileInfo_list.size(); i++) {
                                                SharedPreferencesUtils.setParam(VideoActivity.this, FileInfo_list.get(i).getFileID() + "", FileInfo_list.get(i).getFileDir());
                                                if (FileInfo_list.get(i).getFileName().contains(".mp3") ||
                                                        FileInfo_list.get(i).getFileName().contains(".wav") ||
                                                        FileInfo_list.get(i).getFileName().contains(".wma")) {

                                                    mp3list.add(FileInfo_list.get(i).getFileID() + "");
                                                }
                                            }
                                            //通过获取到的数据，加载教材

                                            fileDir = FileInfo_list.get(0).getFileDir();
                                            mFileID = FileInfo_list.get(0).getFileID();
                                            mPageNums = Integer.parseInt(FileInfo_list.get(0).getPageNums());
                                            //拼接成第一个教材地址URL

                                            mUrl1 = Constant.getDocUrl() + fileDir + "/" + "1.jpg";
                                            LogUtil.i(TAG, "第一个教材地址URL: " + mUrl1);
                                        } else {
                                            fileDir = fileDirWhiteBorad;
                                            mFileID = 1;
                                            currentPage = 1;
                                            mPageNums = 10;
                                            mUrl1 = Constant.getDocUrl() + fileDir + "/" + "1.jpg";
                                        }

                                        mCatalogLists = new ArrayList<>();
                                        for (int i= 0; i < FileInfo_list.size(); i++) {
                                            String fileName = FileInfo_list.get(i).getFileName();
                                            String fileDir = "IdHYwoLGnCVXctW";
                                            if (fileName.contains(".mp3") || fileName.contains(".wav") || fileName.contains(
                                                    ".wma"))
                                            {
                                            } else {
                                                fileDir = FileInfo_list.get(i).getFileDir();
                                            }
                                            String pageNums = FileInfo_list.get(i).getPageNums();
                                            int fileId = FileInfo_list.get(i).getFileID();
                                            CatalogBean catalogBean = new CatalogBean(fileName, fileDir,
                                                                            pageNums, 1, fileId);
                                            catalogBean.setFileType("JPG");
                                            mCatalogLists.add(catalogBean);
                                        }

                                        mH5List = new ArrayList<>();
                                        if (courseinfojson.has("HtmlFileInfo")) {
                                            JSONArray htmlFileInfo = courseinfojson.getJSONArray("HtmlFileInfo");

                                            for (int i = 0; i < htmlFileInfo.length(); i++) {
                                                JSONObject H5JsonObject = htmlFileInfo.getJSONObject(i);
                                                FileInfo fileInfo = mGson.fromJson(H5JsonObject.toString(), FileInfo.class);
                                                mH5List.add(fileInfo);
                                                FileInfo_list.add(fileInfo);
                                                String filename = fileInfo.getFileName();
                                                String filedir = fileInfo.getFileDir();
                                                String pagenum = fileInfo.getPageNums();
                                                int fileid = fileInfo.getFileID();
                                                CatalogBean h5CatalogBean = new CatalogBean(filename, filedir, pagenum,
                                                                                            1, fileid);
                                                h5CatalogBean.setFileType("H5");
                                                mCatalogLists.add(h5CatalogBean);
                                            }
                                        }

                                        if (mH5List.size() > 0) {
                                            startWebMode(true);
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    OpenWebCommandBean.MessageBean messageBean = new OpenWebCommandBean.MessageBean();
                                                    OpenWebCommandBean.MessageBean.WhiteboardBean whiteboardBean = new OpenWebCommandBean.MessageBean.WhiteboardBean();

                                                    mFileID = mH5List.get(0).getFileID();
                                                    fileDir = mH5List.get(0).getFileDir();
                                                    whiteboardBean.setFilename(mH5List.get(0).getFileName());
                                                    whiteboardBean.setFiledir(mH5List.get(0).getFileDir());
                                                    whiteboardBean.setDocserver(Constant.getH5BASEURL());
                                                    whiteboardBean.setSubcommand("openweb");
                                                    whiteboardBean.setCurrentpage(1);
                                                    whiteboardBean.setCurrentaction(0);
                                                    whiteboardBean.setPagenum(0);
                                                    whiteboardBean.setFileid(mFileID);

                                                    messageBean.setType("whiteboard");
                                                    messageBean.setWhiteboard(whiteboardBean);
                                                    openWeb(messageBean);
                                                }
                                            });
                                        }
                                    }
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {

                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        loadImageBitmap(mUrl1);
        mTimerView.setTitleText(roomName);
        switch (mRoomType) {
            case 1:
                mTimerView.setImage(R.drawable.bar_1_v_1_class);
                break;
            case 2:
                mTimerView.setImage(R.drawable.bar_small_class);
                break;
            case 3:
                mTimerView.setImage(R.drawable.bar_large_class);
                break;
        }
    }

    /**
     * 校验协议时效性
     * @return
     */
    private void verifyConnectionTime(final String type, final long timestamp) {

        VerificationKeyUtils keyUtils = new VerificationKeyUtils();
        String VerificationKey = keyUtils.getVerificationKey(Info.MECHANISM_ID);

        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("UA", "Android");
        params.addBodyParameter("Version", Info.APIVERSION);
        params.addBodyParameter("VerificationKey", VerificationKey);

        httpUtils.send(HttpRequest.HttpMethod.POST, Constant.getTimestampUrl(), params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                try {
                    JSONObject responseJson;
                    responseJson = new JSONObject(responseInfo.result);

                    String result = responseJson.getString("Result");
                    if (result.equals("true")) {
                        final String connTime = responseJson.getString("Unix");
                        LogUtil.e("timestamp", connTime + "||" + timestamp);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (type.equals("time")) {
                                    mTimerView.setDate(connTime);
                                } else if(type.equals("voucher")) {
                                    if (timestamp != 0 && Long.parseLong(connTime) - timestamp > 30 * 60) {
                                        AlertDialog alertDialog = new AlertDialog.Builder(VideoActivity.this).setTitle(
                                                getResources().getString(R.string.course_agreement_has_lapsed)).setIcon(
                                                android.R.drawable.ic_dialog_info).setPositiveButton(
                                                getResources().getString(R.string.course_sure),
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog,
                                                                        int which)
                                                    {
                                                        finish();
                                                        System.exit(0);
                                                    }
                                                }).show();

                                        alertDialog.setCanceledOnTouchOutside(false);
                                        alertDialog.setCancelable(false);
                                        alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                                            @Override
                                            public boolean onKey(DialogInterface dialog,
                                                                 int keyCode,
                                                                 KeyEvent event)
                                            {
                                                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                                                    return true;
                                                }

                                                return false;
                                            }
                                        });
                                    } else {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                VaildAgreement();
                                            }
                                        });
                                    }
                                }
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                ThreadUtils.runOnMainThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.showToast(VideoActivity.this, getResources().getString(R.string.course_get_time_stamp_failed));
                    }
                });
            }

        });
    }

    /**更新显示计时器时间*/
    private void updateView() {
        String hourStr = "";
        String minuteStr = "";
        String secondStr = "";
        timeusedinsec += 1;
        int hour = (int) (timeusedinsec / 3600) % 60;
        int minute = (int) (timeusedinsec / 60) % 60;
        int second = (int) (timeusedinsec % 60);
        if (hour < 10) {
            hourStr = "0" + hour;
        }else{
            hourStr = "" + hour;
        }
        if (minute < 10) {
            minuteStr = "0" + minute;
        } else {
            minuteStr = "" + minute;
        }
        if (second < 10) {
            secondStr = "0" + second;
        } else {
            secondStr = "" + second;
        }
        mTimerView.setTime(hourStr, minuteStr, secondStr);
    }

    /**设置计时器*/
    private void setTimerDate(final ClockBean clockBean) {
        LogUtil.i("时钟消息",clockBean.toString());
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (clockBean.getSubcommand().equals("start")) { // 计时开始
                    timeusedinsec = 0;
                    updateView();
                } else if (clockBean.getSubcommand().equals("sync")) { //同步计时器
                    timeusedinsec = clockBean.getSecondcounts();
                    updateView();
                } else if (clockBean.getSubcommand().equals("stop")) { //停止计时器
                    mClockHandler.removeMessages(1);
                }
            }
        });
        mClockHandler.removeMessages(1);
        mClockHandler.sendEmptyMessageDelayed(1, 1000);
    }


    @Override
    public void onProvideAssistData(Bundle data) {
        super.onProvideAssistData(data);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Video Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        if(mClient!=null) {
            mClient.connect();
            AppIndex.AppIndexApi.start(mClient, getIndexApiAction());
        }
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        if (mClient != null) {
            AppIndex.AppIndexApi.end(mClient, getIndexApiAction());
            mClient.disconnect();
            //rtcEngine.stopPreview();
        }
    }

    private void upLoadCurrentTextBook(String fileDir, int currentPage) {
        //egine.SendGroupMessage();

        LogUtil.e("mFileID", mFileID + "||" + mFileName);

        SendPageturnMessge.sendMessge(fileDir, mFileID, currentPage, mPageNums, egine, mGroup);
    }

    //监听返回按键back
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_UP:// 音量增大
                am.adjustStreamVolume(AudioManager.STREAM_SYSTEM,AudioManager.ADJUST_RAISE,
                                      AudioManager.FX_FOCUS_NAVIGATION_UP);
                break;

            case KeyEvent.KEYCODE_VOLUME_DOWN:// 音量减小
                am.adjustStreamVolume(AudioManager.STREAM_SYSTEM,AudioManager.ADJUST_LOWER,
                                      AudioManager.FX_FOCUS_NAVIGATION_UP);
                break;

            default:
                break;
        }

        return super.onKeyDown(keyCode, event);
    }

    // 用户注册
    private void doRegister(final int user_id, final String user_name, final int user_type) {

        IMInstance talk = new IMInstance(VideoActivity.this);
        if (egine == null) {
            egine = new IMEgine(talk);
        }
        /***
         * IM强制注册
         */
        ThreadUtils.runOnSubThread(new Runnable() {
            @Override
            public void run() {
                egine.RegisterForce(user_id, user_name, user_type, "TestGroupAppkey");
            }
        });

        LogUtil.i(TAG, "doRegister mUserID " + user_id + "-" + user_name + "mUserType -" + user_type);
    }

    /***
     * IM 接收到的信息，然后分类处理
     *
     * @param data
     */
    @Override
    public void OnReceiveGroupMessage(String data) {
        LogUtil.i(TAG, "OnReceiveGroupMessage接收到的数据_" + data);
        FileLogUtils.write("OnReceiveGroupMessage： " + data, true);

        try {

            jsonObject = new JSONObject(data);
            msgjson = (JSONObject) jsonObject.get("message");

            if (msgjson.getString("type").equals("chat")) {
                // 对文档聊天信息

                String bodyjson = msgjson.getString("body");

                if (mChatMsgLists == null) {
                    mChatMsgLists = new ArrayList<>();
                }
                if (mGson == null) {
                    mGson = new Gson();
                }

                VideoBody chatMsgBodybean = mGson.fromJson(bodyjson, VideoBody.class);
                if (chatMsgBodybean.getUsertype() == 4) {
                    chatMsgBodybean.setUser(getString(R.string.system_msg));
                }
                mChatMsgLists.add(chatMsgBodybean);

                LogUtil.e("ChatMsg", mChatMsgLists.size() + "---");

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        if (member_pressed) {
                            mIvMessage.setVisibility(View.VISIBLE);
                        } else {
                            if (mChatHistoryAdapter == null) {
                                mChatHistoryAdapter = new ChatHistoryAdapter(VideoActivity.this, mChatMsgLists);
                                mLvChatMember.setAdapter(mChatHistoryAdapter);
                            } else {
                                mChatHistoryAdapter.updateData(mChatMsgLists);
                            }
                            mLvChatMember.setSelection(mChatHistoryAdapter.getCount());
                        }
                    }
                });

            } else if (msgjson.getString("type").equals("member")) {
                // 进入到成员显示列表
                mDzBean = mGson.fromJson(msgjson.toString(), DzBean.class);

                if (mDzBean.getSubcommand().equals("like")) {

                    int mDzBeanUserid = mDzBean.getUserid();

                    if (userlist != null) {
                        for (int i = 0; i < userlist.size(); i++) {
                            if (userlist.get(i).getUserid().equals(mDzBeanUserid + "")) {
                                likenum = userlist.get(i).getLikenum();
                                final String username = userlist.get(i).getUsername();
                                lnum = likenum + 1;
                                LogUtil.i("like"," --likenum "+likenum +"-lnum-"+lnum);
                                userlist.get(i).setLikenum(lnum);

                                ThreadUtils.runOnMainThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        ToastUtils.showToast(VideoActivity.this,username+getResources().getString(R.string.get_a_like));
                                    }
                                });

                            }
                        }
                    }

                    if(mDzBeanUserid == mUserID){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showGif();
                            }
                        });
                    }

                    if (userlist != null) {
                        mSourceDateList = SortUtils.filledData(mCharacterParser, userlist);
                        // 根据a-z进行排序源数据
                        Collections.sort(mSourceDateList, mPinyinComparator);
                    }
                    if (mSortMemberAdapter == null) {
                        mSortMemberAdapter = new SortMemberAdapter(VideoActivity.this, mSourceDateList, mHostID,mUserID,mUserType,mRoomType,this);
                        mSortMemberAdapter.mAnchorID = mAnchorID;
                    }
                    ThreadUtils.runOnMainThread(new Runnable() {
                        @Override
                        public void run() {
                            mSortMemberAdapter.updateListView(mSourceDateList);
                            mSortMemberAdapter.notifyDataSetChanged();
                        }
                    });

                } else if (mDzBean.getSubcommand().equals("goout")) {
                    /**
                     * 请离教室
                     */
                    if (msgjson.getInt("userid") == mUserID) {
                        //IM断开连接
                        ThreadUtils.runOnSubThread(new Runnable() {
                            @Override
                            public void run() {
                                egine.UnRegister();
                            }
                        });
                        //Agora断开连接
                        rtcEngine.leaveChannel();
                        // 音乐关闭
                        musicRelease();

                        Message msg = Message.obtain();
                        msg.what = GOOUT;
                        mClockHandler.sendMessage(msg);
                    }

                } else if (mDzBean.getSubcommand().equals("limittalk")) {
                    /**
                     *  禁言模式
                     */
                    try {
                        if (mOperationMenuBeanList != null) {
                            for (OperationMenuBean operationMenuBean : mOperationMenuBeanList) {
                                if(operationMenuBean.getUseId().equals(mDzBean.getUserid() + "")){
                                    operationMenuBean.setSpeakStatus(false);
                                }else if(mDzBean.getUserid() == -1){
                                    operationMenuBean.setSpeakStatus(false);
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (mUserType == 3) {
                                                promotedActionsLibrary.menuLimitAllButton.setImageDrawable(
                                                        ContextCompat.getDrawable(
                                                        getApplicationContext(), R.drawable.ic_menu_limittalk));
                                                promotedActionsLibrary.menuLimitAllButton.setSelected(true);
                                                promotedActionsLibrary.menuLimitAllButton.setEnabled(true);
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if ((mDzBean.getUserid() == mUserID || mDzBean.getUserid() == -1) && mUserType != 4) {

                        Message msg = Message.obtain();
                        msg.what = LIMITTALK;
                        mClockHandler.sendMessage(msg);
                    }

                } else if (mDzBean.getSubcommand().equals("allowtalk")) {
                    try {
                        if (mOperationMenuBeanList != null) {
                            for (OperationMenuBean operationMenuBean : mOperationMenuBeanList) {
                                if(operationMenuBean.getUseId().equals(mDzBean.getUserid() + "")){
                                    operationMenuBean.setSpeakStatus(true);
                                }else if(mDzBean.getUserid() == -1){
                                    operationMenuBean.setSpeakStatus(true);
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (mUserType == 3) {
                                                promotedActionsLibrary.menuLimitAllButton.setImageDrawable(
                                                        ContextCompat.getDrawable(
                                                        getApplicationContext(), R.drawable.ic_menu_allowtalk));
                                                promotedActionsLibrary.menuLimitAllButton.setSelected(false);
                                                promotedActionsLibrary.menuLimitAllButton.setEnabled(true);
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    /**
                     *  取消禁言
                     */
                    if ((mDzBean.getUserid() == mUserID || mDzBean.getUserid() == -1) && mUserType != 4){
                        Message msg = Message.obtain();
                        msg.what = ALLOWTALK;
                        mClockHandler.sendMessage(msg);
                    }

                } else if (mDzBean.getSubcommand().equals("changehost")) {//切换主讲

                    mAnchorID = msgjson.getInt("userid");

                    if (mUserID == mAnchorID) {
                        if (mUserID == mHostID) {
                            rtcEngine.leaveChannel();
                            rtcEngine.joinChannel(channelkey, mRoomID + "", "", mUserID);
                        }

                        rtcEngine.setClientRole(1, "");
                        mAnchor = true;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                setupLocalVideo(mFlRemoteVideoViewContainer);
                                frameLayoutMenu.setVisibility(View.VISIBLE);
                                showOrHideMenu(false);//悬浮菜单
                                upLoadCurrentTextBook(fileDir, currentPage);
                                Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_change_to_be_anchor), Toast.LENGTH_SHORT).show();
                            }
                        });
                        rtcEngine.setVideoProfile(Constants.VIDEO_PROFILE_240P, true);
                    }
                    else {
                        if (mUserID != mHostID) {
                            rtcEngine.setClientRole(2, "");
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mUserType == 2) {
                                        frameLayoutMenu.setVisibility(View.GONE);
                                        showOrHideMenu(true);//悬浮菜单
                                    }
                                }
                            });
                            mAnchor = false;
                        } else {
                            rtcEngine.muteLocalVideoStream(true);
                        }
                    }
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //chat_lv.setAdapter(memberAdapter);
                        if (mViewMember.getVisibility() == View.VISIBLE) {
                            mSourceDateList = SortUtils.filledData(mCharacterParser, userlist);
                            mSortMemberAdapter.mAnchorID = mAnchorID;
                            mSortMemberAdapter.updateListView(mSourceDateList);
                        }
                    }
                });

            } else if (msgjson.getString("type").equals("media")) {
                // 进入到media
                if(msgjson.getString("subcommand").equals("switchToVideo")) {
                    isVideoMode = true;
                    switchToVideoMode();
                }
                if(msgjson.getString("subcommand").equals("switchToAudio")){
                    isVideoMode = false;
                    switchToAudioMode();
                }

                micCameraBean = mGson.fromJson(msgjson.toString(), MicCameraBean.class);
                if (micCameraBean.getSubcommand().equals("camera")) {
                    if (mOperationMenuBeanList != null) {
                        for (OperationMenuBean operationMenuBean : mOperationMenuBeanList) {
                            if(operationMenuBean.getUseId().equals(micCameraBean.getUserid() + "")){
                                if (micCameraBean.getSwitchX().equals("on")) {
                                    operationMenuBean.setVideoStatus(true);
                                } else if (micCameraBean.getSwitchX().equals("off")) {
                                    operationMenuBean.setVideoStatus(false);
                                }
                            }
                        }
                    }

                    if (micCameraBean.getSwitchX().equals("on")) {
                        boolean flag = false;
                        for (int j = 0; j < mUserIdLists.size(); j++) {
                            if (mUserIdLists.get(j).equals(micCameraBean.getUserid() + "")) {
                                flag = true;
                            }
                        }

                        if (micCameraBean.getUserid() == mUserID) {
                            rtcEngine.muteLocalVideoStream(false);
                            rtcEngine.enableLocalVideo(true);

                            ThreadUtils.runOnMainThread(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtils.showToast(VideoActivity.this,
                                                         getResources().getString(
                                                                 R.string.course_detail_live_restart_local_video));
                                }
                            });

                            if (!flag) {
                                mUserIdLists.add(0, micCameraBean.getUserid() + "");
                            }
                        } else {
                            if (!flag) {
                                mUserIdLists.add(micCameraBean.getUserid() + "");
                            }
                        }

                    } else if(micCameraBean.getSwitchX().equals("off")){
                        if (micCameraBean.getUserid() == mUserID) {
                            rtcEngine.muteLocalVideoStream(true);
                            rtcEngine.enableLocalVideo(false);
                            ThreadUtils.runOnMainThread(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtils.showToast(VideoActivity.this, getResources().getString(R.string.course_detail_live_mute_local_video));
                                }
                            });
                        }
                        for (int j = 0; j < mUserIdLists.size(); j++) {
                            if (mUserIdLists.get(j).equals(micCameraBean.getUserid() + "")) {
                                mUserIdLists.remove(j);
                                if (mCurrentMultiVideoNum >= j) {
                                    mCurrentMultiVideoNum--;
                                }
                            }
                        }
                    }

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            LogUtil.e("vediow", "::" + mUserIdLists.size() + "||" + mCurrentMultiVideoNum);

                            if (mRoomType != 3) {
                                if (mUserIdLists.size() > 0) {
                                    mCurrentMultiVideoNum = mCurrentMultiVideoNum < 0 ? 0 : mCurrentMultiVideoNum;
                                    if (mUserID == Integer.parseInt(mUserIdLists.get(mCurrentMultiVideoNum))) {
                                        setupLocalVideo(mFlLocalVideoViewContainer);
                                    } else {
                                        setupVideoStream(Integer.parseInt(mUserIdLists.get(mCurrentMultiVideoNum)), mFlLocalVideoViewContainer);
                                    }
                                }else {
                                    mFlLocalVideoViewContainer.removeAllViews();
                                    mLlLocalVideoContainer.setBackgroundResource(R.drawable.defautteacherimage);
                                }
                                drawIndicator(mCurrentMultiVideoNum, mUserIdLists.size());
                            }
                        }
                    });
                }
                //是否暂停本地音频
                else if (micCameraBean.getSubcommand().equals("mic")){
                    if (mOperationMenuBeanList != null) {
                        for (OperationMenuBean operationMenuBean : mOperationMenuBeanList) {
                            if(operationMenuBean.getUseId().equals(micCameraBean.getUserid() + "")){
                                if(micCameraBean.getSwitchX().equals("on")){
                                    operationMenuBean.setMicStatus(true);
                                } else if (micCameraBean.getSwitchX().equals("off")) {
                                    operationMenuBean.setMicStatus(false);
                                }
                            }
                        }
                    }

                    if (micCameraBean.getUserid() == mUserID && micCameraBean.getSwitchX().equals("on")) {
                        rtcEngine.muteLocalAudioStream(false);
                        ThreadUtils.runOnMainThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.showToast(VideoActivity.this, getResources().getString(R.string.course_detail_live_open_local_audio));
                            }
                        });
                    } else if(micCameraBean.getUserid() == mUserID && micCameraBean.getSwitchX().equals("off")) {
                        rtcEngine.muteLocalAudioStream(true);
                        ThreadUtils.runOnMainThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.showToast(VideoActivity.this, getResources().getString(R.string.course_detail_live_close_local_audio));
                            }
                        });
                    }
                }
            } else if (msgjson.getString("type").equals("timer")) {// 返回的是时钟消息
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.showToast(VideoActivity.this, getResources().getString(R.string.course_detail_live_start_class));
                    }
                });
                ClockBean clockBean = mGson.fromJson(msgjson.toString(), ClockBean.class);
                setTimerDate(clockBean);
            } else if (msgjson.getString("type").equals("sharescreen")) { //共享屏幕
                final ShareScreenBean messageBean = mGson.fromJson(msgjson.toString(), ShareScreenBean.class);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (messageBean.getSubcommand().equals("open")) {
                            String liveurl = messageBean.getLiveurl();
                            if (!TextUtils.isEmpty(liveurl)) {
                                playVideoStream(liveurl);
                            }
                        } else if (messageBean.getSubcommand().equals("close")) {
                            stopVideoStream();
                        }
                    }
                });

            } else if (msgjson.getString("type").equals("signin")) {//发起签到
                Toast.makeText(mContext, "签到功能接口", Toast.LENGTH_SHORT).show();

            } else if (msgjson.getString("type").equals("clearroom")) {//清空教室
                ThreadUtils.runOnSubThread(new Runnable() {
                    @Override
                    public void run() {
                        egine.UnRegister();
                    }
                });

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, getString(R.string.clear_room), Toast.LENGTH_SHORT).show();
                        mClockHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                rtcEngine.leaveChannel();
                                finish();
                            }
                        }, 500);
                    }
                });

            } else if (msgjson.getString("type").equals("system")) {//系统消息
                final String systemMsg = msgjson.getString("text");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, systemMsg, Toast.LENGTH_LONG).show();
                    }
                });
            }else if (msgjson.getString("type").equals("reconnect")) {//IM重连消息
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ReconnectIMBean.MessageBean messageBean = mGson.fromJson(msgjson.toString(), ReconnectIMBean.MessageBean.class);
                        int reconnectUserid = messageBean.getUserid();
                        String useraccount = messageBean.getUseracount();
                        String userName = useraccount.split(":|@")[1];

                        if (reconnectUserid == mHostID) {
                            Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_teacher_reconnect), Toast.LENGTH_SHORT).show();
                        } else {
                            if(mRoomType == 1 || (mRoomType == 2 && mUserID == mHostID)){
                                Toast.makeText(VideoActivity.this,
                                               userName + getResources().getString(R.string.course_detail_user_reconnect),
                                               Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                });

            } else {
                LogUtil.i(TAG, "收到的是白板消息_" + jsonObject.toString());
                /***
                 * 排除了其他几种可能，剩下的就只可能是白板数据
                 */
                wbjson = (JSONObject) jsonObject.get("message");
                wbdata = wbjson.getString("whiteboard");

                js = new JSONObject(wbdata);
                subType = (String) js.get("subcommand");
                if (subType.equals("removeobject")) {//撤销 命令
                    //画笔轨迹id
                    try {
                        int objid = (int)js.getJSONArray("objid").get(0);
                        if (mGraffitiView != null) {
                            mGraffitiView.undoServer(objid + "");
                        }
                    } catch (Exception e) {
                        long objid = (long)js.getJSONArray("objid").get(0);
                        if (mGraffitiView != null) {
                            mGraffitiView.undoServer(objid + "");
                        }
                    }

                } else if (subType.equals("textchanged")) {//原有画笔文字的修改
                    //画笔轨迹id
                    int objid = js.getInt("objid");
                    JSONObject objdate = (JSONObject) js.get("objdata");
                    int fontsize = objdate.getInt("fontsize");//画笔大小
                    String text = objdate.getString("string");//修改后的文字

                    if (mGraffitiView != null) {
                        mGraffitiView.undoTextChangeServer(objid, text);
                    }
                }
                /***
                 * 打开一个文档 ,分多种情况
                 */
                else if (subType.equals("openfile")) {

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            startWebMode(false);
                        }
                    });

                    docUrl = Constant.getDocUrl() + fileDirWhiteBorad + "/1.jpg";
                    LogUtil.d(TAG, ">>>>>>>>>>>>>>openfile");

                    if (!msgjson.has("authorization")) {
                        /**
                         * 手动上传
                         */
                        bigmsgjson = (JSONObject) jsonObject.get("message");

                        bigwbdata = bigmsgjson.getString("whiteboard");
                        mWhiteBoardBean = mGson.fromJson(bigwbdata, WhiteBoardBean.class);

                        bigdata = new JSONObject(bigwbdata);
                        doc_fileid = bigdata.getString("fileid");
                        doc_server = bigdata.getString("docserver");
                        fileDir = bigdata.getString("filedir");
                        String filename = bigdata.getString("filename");

                        if(filename.contains(".mp3") || filename.contains(".wav") || filename.contains(".wma")){
                            fileDir = Constant.WHITEBOARDFILEDIR;
                        }

                        doc_pagenum = bigdata.getString("currentpage");
                        currentPage = Integer.valueOf(doc_pagenum);
                        mTeacherCurrentPage = currentPage;

                        if ( bigdata.has("pagenum") ) {
                            mPageNums = bigdata.getInt("pagenum");LogUtil.i("mPageNums", "mPageNums = "+mPageNums);
                        }

                        docUrl = doc_server + fileDir + "/" + doc_pagenum + ".jpg";

                        //把老师自己上传的doc存到sp中
                        SharedPreferencesUtils.setParam(VideoActivity.this, doc_fileid, fileDir);

                        SharedPreferencesUtils.setParam(VideoActivity.this, doc_fileid + "pagenum", mPageNums);

                        LogUtil.i(TAG, "loadImage   老师自己上传教材地址 " + docUrl);
                        LogUtil.i(TAG, "5555");
                        loadImageBitmap(docUrl);
                        boolean isFileExist = false;
                        if(mCatalogLists != null){
                            for (CatalogBean catalogList : mCatalogLists) {
                                if (catalogList.getFileId() == Integer.parseInt(doc_fileid)) {
                                    isFileExist = true;
                                    break;
                                }
                            }
                        }else {
                            mCatalogLists = new ArrayList<>();
                        }

                        if (!isFileExist) {
                            CatalogBean catalogBean = new CatalogBean(bigdata.getString("filename"),
                                                                    fileDir, mPageNums + "",
                                                                    currentPage,
                                                                    Integer.parseInt(doc_fileid));
                            catalogBean.setFileType("JPG");
                            mCatalogLists.add(catalogBean);
                        }
                    } else {
                        /**
                         * 自动openfile 存对应id的 filedir
                         */
                        LogUtil.i(TAG, "自动openfile 存对应id的 filedir");

                        AuthOpenFile authOpenFile = mGson.fromJson(jsonObject.toString(), AuthOpenFile.class);

                        SharedPreferencesUtils.setParam(VideoActivity.this, authOpenFile.getMessage().getWhiteboard().getFileid() + "",
                                authOpenFile.getMessage().getWhiteboard().getFiledir());

                        SharedPreferencesUtils.setParam(VideoActivity.this, authOpenFile.getMessage().getWhiteboard().getFileid() + "pagenum",
                                authOpenFile.getMessage().getWhiteboard().getPagenum());

                        LogUtil.i(TAG, "id  " + authOpenFile.getMessage().getWhiteboard().getFileid() + "  filedir  " + authOpenFile.getMessage().getWhiteboard().getFiledir());
                    }

                } else if (subType.equals("pageturn")) {
                    //mediaPlayer = null;//防止音乐不翻页
                    mWhiteBoardBean = mGson.fromJson(wbdata, WhiteBoardBean.class);
                    LogUtil.d(TAG, "翻页>>>>>>>>>>>>>>>pageturn  fileid " + mWhiteBoardBean.getFileid());

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            startWebMode(false);
                            mRlMusic.setVisibility(View.GONE);
                            mFrameLayout.setVisibility(View.VISIBLE);
                        }
                    });

                    if (msgjson.has("sqlid")) {
                        /**
                         * 自定义教材手动翻页
                         */
                        pageturn_fileid = mWhiteBoardBean.getFileid() + "";
                        currentPage = mWhiteBoardBean.getCurrentpage();
                        mPageNums = (int) SharedPreferencesUtils.getParam(VideoActivity.this, mWhiteBoardBean.getFileid()+"pagenum", 1);
                        LogUtil.i("mPageNums", "mPageNums = "+mPageNums);
                        fileDir = SharedPreferencesUtils.getParam(VideoActivity.this, mWhiteBoardBean.getFileid() + "", "null").toString();
                        mUrl4 = Constant.getDocUrl() + fileDir + "/" + mWhiteBoardBean.getCurrentpage() + ".jpg";

                    } else {
                        /**
                         * 切换教材翻页
                         */
                        pageturn_fileid = mWhiteBoardBean.getFileid() + "";
                        LogUtil.i(TAG, "pageturn_fileid  " + pageturn_fileid);

                        mFileID = mWhiteBoardBean.getFileid();

                        mSyncPage = (mTeacherCurrentPage == currentPage);

                        currentPage = mWhiteBoardBean.getCurrentpage();

                        mTeacherCurrentPage = currentPage;

                        int pagenum = mWhiteBoardBean.getPagenum();
                        mPageNums = (pagenum != 0) ? pagenum : 10;

                        if (FileInfo_list != null) {

                            for (FileInfo fileInfo : FileInfo_list) {
                                if (fileInfo.getFileID() == Integer.parseInt(pageturn_fileid)) {
                                    mPageNums = Integer.parseInt(fileInfo.getPageNums());
                                }
                            }
                        }

                        LogUtil.i("mPageNums", "mPageNums = "+mPageNums);
                        if (mFileID == 1) {
                            fileDir = Constant.WHITEBOARDFILEDIR;
                        } else {
                            fileDir = SharedPreferencesUtils.getParam(VideoActivity.this, mWhiteBoardBean.getFileid() + "", "").toString();
                            if (TextUtils.isEmpty(fileDir)) {
                                fileDir = Constant.WHITEBOARDFILEDIR;
                            }
                        }
                        mUrl4 = Constant.getDocUrl() + fileDir + "/" + mWhiteBoardBean.getCurrentpage() + "" + ".jpg";
                        LogUtil.i(TAG, "7777");
                        if (pageturn_fileid.equals("1") && null!=pageturn_fileid) {
                            mUrl4 = Constant.getDocUrl() + fileDirWhiteBorad + "/" + currentPage +".jpg";
                        }
                    }

                    if (mp3list != null) {

                        LogUtil.i(TAG, " mp3list  " + pageturn_fileid);
                        if (mp3list.contains(pageturn_fileid)) {
                            //MP3集合的元素中，含有此fileid
                            LogUtil.i(TAG, "此资源为音频文件");
                            fileDir = SharedPreferencesUtils.getParam(this, mWhiteBoardBean.getFileid() + "", "null").toString();
                            mp3Url = Constant.getMP3URL() + fileDir + "/1.mp3";

                            mUrl4 = Constant.getDocUrl() + fileDirWhiteBorad + "/1.jpg";

                            mMusicFileName = SharedPreferencesUtils.getParam(this, mWhiteBoardBean.getFileid() + "name", "null").toString();

                            String mp3Name = SharedPreferencesUtils.getParam(VideoActivity.this, pageturn_fileid + "", "").toString();
                            final String mp3Path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/download/" + mp3Name + ".mp3";

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mRlMusic.setVisibility(View.VISIBLE);
                                    mFrameLayout.setVisibility(View.GONE);

                                    if (!IsPlaying) {
                                        mTvMusicName.setText(mMusicFileName);
                                        if (map.containsKey(mp3Path)) {
                                            MediaPlayer mediaPlayer = map.get(mp3Path);
                                            mTvMusicCurrentTime.setText(timeFormat.format(mediaPlayer.getCurrentPosition()));
                                            mTvMusicDuration.setText(timeFormat.format(mediaPlayer.getDuration()));
                                            mSpbMusic.setProgress(mediaPlayer.getCurrentPosition());
                                            mSpbMusic.setMax(mediaPlayer.getDuration());
                                        } else {
                                            mTvMusicCurrentTime.setText("00:00");
                                            mTvMusicDuration.setText("00:00");
                                            mSpbMusic.setProgress(0);
                                        }
                                    }

                                    if (mUserID == mHostID) {
                                        mLlMusicControl.setVisibility(View.VISIBLE);
                                    } else {
                                        mLlMusicControl.setVisibility(View.GONE);
                                    }
                                }
                            });
                        }

                        if (pageturn_fileid.equals("1")) {
                            //包含教材和fileid=1的白板情况
                            //打开白板
                            LogUtil.i(TAG, "跳转到白板页");
                            mUrl4 = Constant.getDocUrl() + fileDirWhiteBorad + "/1.jpg";
                        }
                        LogUtil.i(TAG, "pageturn  mUrl4 " + mUrl4);

                        if (mUrl4 != null) {
                            if (!(mUrl4.endsWith(".aac"))) {
                                if (!mUrl4.contains("null")) {

                                    LogUtil.i(TAG, "6666");
                                    loadImageBitmap(mUrl4);
                                    LogUtil.i(TAG, "loadImage  翻页时候 教材地址 " + mUrl4);
                                }
                            }
                        }

                    } else {
                        LogUtil.i(TAG, "无MP3时候，翻页mUrl4 " + mUrl4);
                        if (!mUrl4.contains("null")) {
                            loadImageBitmap(mUrl4);
                        }
                    }
                    //设置是否显示左右翻页图标
                    ThreadUtils.runOnMainThread(new Runnable() {
                        @Override
                        public void run() {
                            arrowShow();
                        }
                    });

                } else if (subType.equals("removeall")) {// 清屏
                    if (isWebMode) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mWebView.clearGraffiti(mFileID, currentPage);
                            }
                        });
                    } else {
                        if (mGraffitiView != null) {
                            mGraffitiView.clearService();
                            String fileIdKey = mFileID + "-" + currentPage;
                            mGraffitiPaintData.remove(fileIdKey);
                            mGraffitiPathPageMap.remove(fileIdKey);
                        }
                    }

                } else if (subType.equals("lock")) {
                    if (mUserID == mHostID) {
                        return;
                    }
                    LockBean lockBean = mGson.fromJson(wbdata, LockBean.class);

                    int userid = lockBean.getUserid();
                    String status = lockBean.getStatus();

                    for (OperationMenuBean operationMenuBean : mOperationMenuBeanList) {
                        if(operationMenuBean.getUseId().equals(userid + "")){
                            if (status.equals("true")) {
                                operationMenuBean.setLockStatus(true);
                            } else if(status.equals("false")) {
                                operationMenuBean.setLockStatus(false);
                            }
                        }
                    }

                    if(userid==0 && mUserType != 3 && mUserType != 4){
                        if(status.equals("true")){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showOrHideMenu(true);
                                    frameLayoutMenu.setVisibility(View.GONE);
                                    Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_live_receive_lock), Toast.LENGTH_SHORT).show();
                                }
                            });
                        }else{
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showOrHideMenu(false);
                                    frameLayoutMenu.setVisibility(View.VISIBLE);
                                    Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_live_receive_unlock), Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                    }else{
                        if(userid==mUserID){
                            if(status.equals("true")){
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        showOrHideMenu(true);
                                        frameLayoutMenu.setVisibility(View.GONE);
                                        Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_live_receive_lock), Toast.LENGTH_SHORT).show();

                                    }
                                });
                            }else{
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        showOrHideMenu(false);
                                        frameLayoutMenu.setVisibility(View.VISIBLE);
                                        Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_live_receive_unlock), Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        }
                    }
                } else if (subType.equals("audio")) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            startWebMode(false);
                        }
                    });
                    MusicOrderBean whiteBoardBean = mGson.fromJson(wbdata, MusicOrderBean.class);
                    String fileid = whiteBoardBean.getFileid() + "";
                    float time = whiteBoardBean.getTime();
                    String mp3Name = SharedPreferencesUtils.getParam(VideoActivity.this, fileid, "").toString();
                    String mp3Path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/download/" + mp3Name + ".mp3";

                    if (whiteBoardBean.getAction().equals("play")) {

                        LogUtil.i(TAG, "音乐FileID -- " + whiteBoardBean.getFileid() + "音乐秒数 " + time);

                        IsPlaying = true;

                        musicPlay(mp3Path, time * 1000);//方法是毫秒而不是秒

                    } else if (whiteBoardBean.getAction().equals("pause")) {
                        IsPlaying = false;
                        musicPause(mp3Path);
                    } else if (whiteBoardBean.getAction().equals("stop")) {
                        IsPlaying = false;
                        musicStop(mp3Path);
                    }

                }else if(subType.equals("pointer")){ // 指示器
                    PositionXYBean positionXYBean = mGson.fromJson(wbdata, PositionXYBean.class);
                    drawPosition(positionXYBean);

                }else if (subType.equals("openweb")) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            startWebMode(true);

                            OpenWebCommandBean.MessageBean openMessageBean = mGson.fromJson(
                                    wbjson.toString(), OpenWebCommandBean.MessageBean.class);

                            openWeb(openMessageBean);
                        }
                    });
                } else if (subType.equals("webturn")) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            startWebMode(true);

                            WebTurnCommandBean.MessageBean webturnMessageBean = mGson.fromJson(
                                    wbjson.toString(), WebTurnCommandBean.MessageBean.class);
                            webTurn(webturnMessageBean);
                        }
                    });
                } else if (subType.equals("webmedia")) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            startWebMode(true);

                            WebMediaBean.MessageBean webMediaMessageBean = mGson.fromJson(
                                    wbjson.toString(), WebMediaBean.MessageBean.class);

                            processWebMedia(webMediaMessageBean);
                        }
                    });
                }else if (subType.equals("addgraffiti")) {
                    //web画笔涂鸦
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            AddGraffitiBean.MessageBean.WhiteboardBean webWhiteboardBean = mGson.fromJson(
                                    wbdata, AddGraffitiBean.MessageBean.WhiteboardBean.class);

                            int currentpage = webWhiteboardBean.getCurrentpage();
                            if (mUserID != mHostID && currentpage != currentPage) {
                                currentPage = currentpage;
                                mCurrentaction = 0;
                                mWebView.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        mWebView.loadUrl(
                                                "javascript:Presentation.JumpToAnim(" + mCurrentaction + "," + currentPage + ",1)");
                                    }
                                });
                            }

                            if (webWhiteboardBean.getObjtype().equals("pen")) {
                                GraffitiInfo.GraffitiPageBean.GraffitiDataBean graffitiDataBean = new GraffitiInfo.GraffitiPageBean.GraffitiDataBean();
                                graffitiDataBean.setCoordinates(webWhiteboardBean.getObjdata());
                                graffitiDataBean.setGraffitiId(webWhiteboardBean.getObjid());
                                graffitiDataBean.setGraffitiColor(webWhiteboardBean.getColour());
                                mWebView.drawGraffiti(graffitiDataBean);
                            }else {
                                GraffitiShapeBean graffitiShapeBean = new GraffitiShapeBean();
                                AddGraffitiBean.MessageBean.WhiteboardBean.RectBean rectBean = webWhiteboardBean.getRect();
                                graffitiShapeBean.setShape(webWhiteboardBean.getObjtype());
                                graffitiShapeBean.setColor(webWhiteboardBean.getColour());
                                graffitiShapeBean.setText(webWhiteboardBean.getString());
                                graffitiShapeBean.setLeft(rectBean.getLeft());
                                graffitiShapeBean.setTop(rectBean.getTop());
                                graffitiShapeBean.setRight(rectBean.getRight());
                                graffitiShapeBean.setBottom(rectBean.getBottom());
                                mWebView.drawGraffitiShape(webWhiteboardBean.getFileid(), graffitiShapeBean);
                            }
                        }
                    });
                } else if (subType.equals("removegraffiti")) {
                    final int objid = js.getInt("objid");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (isWebMode) {
                                mWebView.revokeGraffiti(objid);
                            }
                        }
                    });
                } else if (subType.equals("webconsole")) {
                    final int currentpage = js.getInt("currentpage");
                    mTeacherCurrentPage = currentpage;

                    final String console = js.getString("console");

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            if (console.contains("onPageup") || console.contains("onPagedown") || console.contains("onJumpPage")) {
                                currentPage = currentpage;
                                String jumpConsole = "{\"method\":\"onJumpPage\",\"toPage\":" + currentPage + "}";
                                mWebView.loadUrl("javascript:postMessage('" + jumpConsole + "','*');");
                            } else {
                                if (currentpage != currentPage) {
                                    currentPage = currentpage;
                                    String jumpConsole = "{\"method\":\"onJumpPage\",\"toPage\":" + currentPage + "}";
                                    mWebView.loadUrl("javascript:postMessage('" + jumpConsole + "','*');");
                                }

                                mWebView.loadUrl("javascript:postMessage('" + console + "','*');");
                            }
                            mPageText.setText(currentPage + "/" + mPageNums);
                        }
                    });
                } else {// 画笔
                    //addobject
                    if (js.has("objtype")) {
                        String objtype = js.getString("objtype");
                        LogUtil.i(TAG, "objtype  " + objtype);

                        if (objtype.equals("text")) {//画笔，文字
                            textWhiteBoardBean = mGson.fromJson(jsonObject.toString(),
                                                                TextWhiteBoardBean.class);
                            if (textWhiteBoardBean.getMessage()
                                                  .getWhiteboard()
                                                  .getCurrentpage() != currentPage)
                            {
                                if (mUserType != 1) {
                                    //学生端和老师端教材不同页，此时老师使用画笔
                                    differentPageText = true;
                                    if ("1".equals(mWhiteBoardBean.getFileid())) {
                                        String url = Constant.getDocUrl() + fileDirWhiteBorad + "/" + mWhiteBoardBean
                                                .getCurrentpage() + ".jpg";
                                        loadImageBitmap(url);
                                    } else {
                                        String url = Constant.getDocUrl() + mWhiteBoardBean.getFiledir() + "/" + mWhiteBoardBean
                                                .getCurrentpage() + ".jpg";
                                        loadImageBitmap(url);
                                    }
                                    currentPage = textWhiteBoardBean.getMessage()
                                                                    .getWhiteboard()
                                                                    .getCurrentpage();
                                    textWhiteBoardBean.getMessage()
                                                      .getWhiteboard()
                                                      .setFiledir(fileDirWhiteBorad);
                                    //设置是否显示左右翻页图标
                                    ThreadUtils.runOnMainThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            arrowShow();
                                        }
                                    });
                                }

                            } else {
                                if (mGraffitiView != null) {
                                    mGraffitiView.storeGraffitiTextData(
                                            textWhiteBoardBean.getMessage());
                                    doPaintTextGraffiti(textWhiteBoardBean);
                                }
                            }
                        } else {
                            //画笔部分

                            mWhiteBoardBean = mGson.fromJson(wbdata, WhiteBoardBean.class);

                            if (mWhiteBoardBean.getCurrentpage() != currentPage) {
                                if (mUserType != 1) {
                                    //学生端和老师端教材不同页，此时老师使用画笔
                                    differentPage = true;
                                    if ("1".equals(mWhiteBoardBean.getFileid())) {
                                        String url = Constant.getDocUrl() + fileDirWhiteBorad + "/" + mWhiteBoardBean
                                                .getCurrentpage() + ".jpg";
                                        loadImageBitmap(url);
                                    } else {
                                        String url = Constant.getDocUrl() + mWhiteBoardBean.getFiledir() + "/" + mWhiteBoardBean
                                                .getCurrentpage() + ".jpg";
                                        loadImageBitmap(url);
                                    }
                                    currentPage = mWhiteBoardBean.getCurrentpage();
                                    mWhiteBoardBean.setFiledir(fileDirWhiteBorad);
                                    //设置是否显示左右翻页图标
                                    ThreadUtils.runOnMainThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            arrowShow();
                                        }
                                    });
                                }

                            } else {

                                if (mWhiteBoardBean.getSubcommand().equals("addobject")) {
                                    if (mGraffitiView != null) {
                                        mGraffitiView.storeGraffitiLineData(mWhiteBoardBean);
                                        doPaintGraffiti(mWhiteBoardBean);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void processWebMedia(WebMediaBean.MessageBean webMediaMessageBean) {
        WebMediaBean.MessageBean.WhiteboardBean wMediaWhiteboard = webMediaMessageBean.getWhiteboard();
        int fileid = wMediaWhiteboard.getFileid();
        int currentpage = wMediaWhiteboard.getCurrentpage();
        String action = wMediaWhiteboard.getAction();
        final String mediaid = wMediaWhiteboard.getMediaid();
        if (action.equals("play")) {

            if (currentpage != currentPage) {
                currentPage = currentpage;
                mWebView.post(new Runnable() {
                    @Override
                    public void run() {
                        mWebView.loadUrl("javascript:Presentation.GotoSlide(" + currentPage + ")");
                    }
                });
            }

            mWebView.post(new Runnable() {
                @Override
                public void run() {
                    mWebView.loadUrl(
                            "javascript:document.getElementById(\"" + mediaid + "\").play();");
                }
            });

        } else if(action.equals("pause")){
            mWebView.post(new Runnable() {
                @Override
                public void run() {
                    mWebView.loadUrl(
                            "javascript:document.getElementById(\"" + mediaid + "\").pause();");
                }
            });
        }
    }

    private void showGif() {
        mFrescoGif.setVisibility(View.VISIBLE);

        ControllerListener controllerListener = new BaseControllerListener<ImageInfo>() {
            @Override
            public void onFinalImageSet(
                    String id,
                    @Nullable ImageInfo imageInfo,
                    @Nullable final Animatable anim) {
                if (anim != null) {
                    // 其他控制逻辑
                    anim.start();
                    mClockHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            anim.stop();
                            mFrescoGif.setVisibility(View.GONE);
                        }
                    }, 3000);
                }
            }
        };

        Uri uri =Uri.parse("res://"+mContext.getPackageName()+"/" + R.drawable.praise);

        DraweeController controller = Fresco.newDraweeControllerBuilder()
                                            .setUri(uri)
                                            .setControllerListener(controllerListener)
                                            // 其他设置（如果有的话）
                                            .build();
        mFrescoGif.setController(controller);
    }


    private void musicRelease() {
        for (Map.Entry<String, MediaPlayer> entry : map.entrySet()) {
            if(entry.getValue() != null){
                MediaPlayer mediaPlayer = entry.getValue();
                mediaPlayer.stop();
            }
        }

        map.clear();
    }

    private void musicStop(String mp3Url) {

        if (map.containsKey(mp3Url)) {

            MediaPlayer mediaPlayer = map.get(mp3Url);

            if (mediaPlayer == null) {
                return;
            } else {
                mediaPlayer.stop();
                map.remove(mp3Url);
                mClockHandler.removeCallbacks(mRunnable);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTvMusicCurrentTime.setText("00:00");
                        mIvMusicPlayOrPause.setImageResource(R.drawable.selector_music_play);
                        mSpbMusic.setProgress(0);
                    }
                });
            }
        }
    }

    private void musicPause(String mp3Url) {

        if (map.containsKey(mp3Url)) {
            MediaPlayer mediaPlayer = map.get(mp3Url);

            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                mClockHandler.removeCallbacks(mRunnable);
            }

        } else {
            return;
        }
    }

    MediaPlayer mediaPlayer;
    SimpleDateFormat timeFormat = new SimpleDateFormat("mm:ss");
    SimpleDateFormat secondFormat = new SimpleDateFormat("ss");
    public Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            mMusicCurrentPositionTime = secondFormat.format(mediaPlayer.getCurrentPosition());

            mTvMusicCurrentTime.setText(timeFormat.format(mediaPlayer.getCurrentPosition()));
            mSpbMusic.setProgress(mediaPlayer.getCurrentPosition());
            mClockHandler.postDelayed(mRunnable, 100);
        }
    };

    private void musicPlay(final String mp3Url, final float time) {

        for (Map.Entry<String, MediaPlayer> entry : map.entrySet()) {
            if(!entry.getKey().equals(mp3Url)){
                MediaPlayer mediaPlayer = entry.getValue();
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                }
            }
        }

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mUserID != mHostID) {
                    mTvMusicName.setText(mMusicFileName);
                }
            }
        });

        //如果Url没有播放过
        if (!map.containsKey(mp3Url)) {

            LogUtil.i(TAG, "map  长度" + map.size());

            mediaPlayer = new MediaPlayer();

            map.put(mp3Url, mediaPlayer);

            try {
                mediaPlayer.setDataSource(mp3Url);

                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mediaPlayer.setVolume(1.0f, 1.0f);

                mediaPlayer.prepareAsync();

                // 为播放器注册
                mediaPlayer.setOnPreparedListener(new OnPreparedListener() {

                    public void onPrepared(MediaPlayer mp) {
                        mp.seekTo((int)time);
                        mp.start();

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mTvMusicDuration.setText(timeFormat.format(mediaPlayer.getDuration()));
                                mSpbMusic.setMax(mediaPlayer.getDuration());
                                mClockHandler.post(mRunnable);
                            }
                        });
                    }
                });

                // 注册播放完毕后的监听事件
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                    public void onCompletion(MediaPlayer mp) {
                        mp.release();
                        mp = null;
                        if (map.containsKey(mp3Url)) {
                            map.remove(mp3Url);
                            mClockHandler.removeCallbacks(mRunnable);

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mTvMusicCurrentTime.setText("00:00");
                                    mIvMusicPlayOrPause.setImageResource(R.drawable.selector_music_play);
                                    mSpbMusic.setProgress(0);
                                }
                            });
                        }
                    }
                });
                //map.put(mp3Url, mediaPlayer);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            LogUtil.i(TAG, "Url之前播放过，并且存储起来了  " + map.size());
            //Url之前播放过，并且存储起来了
            mediaPlayer = map.get(mp3Url);
            mediaPlayer.start();

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mTvMusicDuration.setText(timeFormat.format(mediaPlayer.getDuration()));
                    mSpbMusic.setMax(mediaPlayer.getDuration());

                    mClockHandler.post(mRunnable);
                }
            });
        }
    }

    private void loadImageBitmap(final String url) {
        LogUtil.i(TAG, "loadImageBitmap教材地址 " + url);
        FileLogUtils.write("loadImageBitmap: " + url, true);
        if (url == null) {
            return;
        }
        if(!url.contains("null")) {
            ThreadUtils.runOnMainThread(new Runnable() {
                @Override
                public void run() {
                    mProgressBar.setVisibility(View.VISIBLE);
                }
            });
        }

        OkGo.get(url)//
            .tag(this)//
            .execute(new BitmapCallback() {
                @Override
                public void onSuccess(Bitmap bitmap, Call call, Response response) {
                    mGraffitiBitmap = bitmap;
                    mGraffitiParams = new GraffitiParams();
                    mGraffitiParams.drawBtimap = mGraffitiBitmap;

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mProgressBar.setVisibility(View.GONE);
                        }
                    });
                    //通过handler更新UI
                    upLoadHanler.sendEmptyMessage(CREATE_DRAW_VIEW);
                    response.close();
                }

                @Override
                public void onError(Call call, Response response, final Exception e) {
                    super.onError(call, response, e);
                    Log.e("TAG","load image url onError");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(VideoActivity.this, e.getMessage() + "||" + url, Toast.LENGTH_SHORT).show();
                            mProgressBar.setVisibility(View.GONE);
                        }
                    });
                }
            });
    }

    //绘制指示器
    private void drawPosition(PositionXYBean positionXYBean) {
        if (mGraffitiView == null) {
            return;
        }

        if ("show".equals(positionXYBean.getStatus())){//显示
            mGraffitiView.setLocation(50, 50);

        }else if ("moving".equals(positionXYBean.getStatus())){//移动
            mGraffitiView.setLocation(positionXYBean.getPositionx(), positionXYBean.getPositiony());

        }else if ("hide".equals(positionXYBean.getStatus())){//隐藏
            mGraffitiView.setLocation(-50, -50);
        }
    }

    // 输入文字
    private void doPaintTextGraffiti(TextWhiteBoardBean textWhiteBoardBean) {
        float top = textWhiteBoardBean.getMessage().getWhiteboard().getRect().getTop();
        float bottom = textWhiteBoardBean.getMessage().getWhiteboard().getRect().getBottom();
        float left = textWhiteBoardBean.getMessage().getWhiteboard().getRect().getLeft();
        float right = textWhiteBoardBean.getMessage().getWhiteboard().getRect().getRight();
        String text = textWhiteBoardBean.getMessage().getWhiteboard().getObjdata().getString();
        int textSize = textWhiteBoardBean.getMessage().getWhiteboard().getObjdata().getFontsize();
        int color = Color.parseColor(ColorUtils.chageColor(textWhiteBoardBean.getMessage().
                getWhiteboard().getObjdata().getColour()));
        int objid = textWhiteBoardBean.getMessage().getWhiteboard().getObjid();//轨迹编号id
        mGraffitiView.setDrawPaintText(left, top, right, bottom, text, color, textSize, objid);
    }

    //画板轨迹
    private void doPaintGraffiti(WhiteBoardBean whiteBoardBean) {
        //轨迹编号id
        int objid = whiteBoardBean.getObjid();

        if (whiteBoardBean.getRect() == null) {
            WhiteBoardBean.RectBean rectBean = new WhiteBoardBean.RectBean();
            int top = (int) whiteBoardBean.getObjdata().get(0).getY();
            int left = (int) whiteBoardBean.getObjdata().get(0).getX();
            int bottom = (int) whiteBoardBean.getObjdata().get(0).getY();
            int right = (int) whiteBoardBean.getObjdata().get(0).getX();
            for (WhiteBoardBean.ObjdataBean coordinates : whiteBoardBean.getObjdata()) {
                top = (coordinates.getY() < top) ? (int) coordinates.getY() : top;
                left = (coordinates.getX() < left) ? (int) coordinates.getX() : left;
                bottom = (coordinates.getY() > bottom) ? (int) coordinates.getY() : bottom;
                right = (coordinates.getX() > right) ? (int) coordinates.getX() : right;
            }
            rectBean.setTop(top);
            rectBean.setLeft(left);
            rectBean.setBottom(bottom);
            rectBean.setRight(right);

            whiteBoardBean.setRect(rectBean);
        }

        //画线
        if (whiteBoardBean.getSubcommand().equals("addobject")
                && whiteBoardBean.getObjtype().equals("pen")) {
            float stratX = whiteBoardBean.getObjdata().get(0).getX();
            float stratY = whiteBoardBean.getObjdata().get(0).getY();
            int color = Color.parseColor(ColorUtils.chageColor(whiteBoardBean.getColour()));
            LogUtil.i("画笔颜色", "color = " + color);
            float paintSize = whiteBoardBean.getLinewidth() + 0.5f;
            mGraffitiView.setPaintSizePost(paintSize);
            int size = whiteBoardBean.getObjdata().size();
            for (int i = 0; i < size; i++) {
                x = whiteBoardBean.getObjdata().get(i).getX();
                y = whiteBoardBean.getObjdata().get(i).getY();
                mGraffitiView.setDrawPaint(stratX, stratY, x, y, size, i, color, paintSize, objid);
                stratX = x;
                stratY = y;
            }
        }
        // 画矩形
        else if (whiteBoardBean.getSubcommand().equals("addobject")
                && whiteBoardBean.getShapetype().equals("emptyrect")) {
            int color = Color.parseColor(ColorUtils.chageColor(whiteBoardBean.getColour()));
            float left = whiteBoardBean.getRect().getLeft();
            float top = whiteBoardBean.getRect().getTop();
            float right = whiteBoardBean.getRect().getRight();
            float bottom = whiteBoardBean.getRect().getBottom();
            mGraffitiView.setDrawPaintEmptyRect(left, top, right, bottom, color, "emptyrect", null, objid);

        }
        // 画圆形
        else if (whiteBoardBean.getSubcommand().equals("addobject")
                && whiteBoardBean.getShapetype().equals("emptyellipse")) {
            int color = Color.parseColor(ColorUtils.chageColor(whiteBoardBean.getColour()));
            float left = whiteBoardBean.getRect().getLeft();
            float top = whiteBoardBean.getRect().getTop();
            float right = whiteBoardBean.getRect().getRight();
            float bottom = whiteBoardBean.getRect().getBottom();
            mGraffitiView.setDrawPaintEmptyRect(left, top, right, bottom, color, "emptyellipse", null, objid);

        }
        // 画直线
        else if (whiteBoardBean.getSubcommand().equals("addobject")
                && whiteBoardBean.getShapetype().equals("line")) {
            int color = Color.parseColor(ColorUtils.chageColor(whiteBoardBean.getColour()));
            float left = whiteBoardBean.getRect().getLeft();
            float top = whiteBoardBean.getRect().getTop();
            float right = whiteBoardBean.getRect().getRight();
            float bottom = whiteBoardBean.getRect().getBottom();
            mGraffitiView.setDrawPaintEmptyRect(left, top, right, bottom, color, "line", null, objid);
        }
    }

    private void getChannelKey(final String roomCode, final String userCode, final String keyType) {
        new Thread(new Runnable() {
            public void run() {
                VerificationKeyUtils keyUtils = new VerificationKeyUtils();
                //String VerificationKey = keyUtils.getVerificationKey(Info.MECHANISM_ID);
                String VerificationKey = keyUtils.getVerificationKey(TalkApplication.getMechanismId());

                HttpUtils httpUtils = new HttpUtils();
                RequestParams params = new RequestParams();
                params.addBodyParameter("ChannelID", roomCode);
                params.addBodyParameter("UserID", userCode);
                params.addBodyParameter("VerificationKey", VerificationKey);

                String url = Constant.getChannelkeyUrl();
                if (keyType.equals("CHANNELKEY")) {
                    url = Constant.getChannelkeyUrl();
                } else if (keyType.equals("RECORDKEY")) {
                    url = Constant.getRecordkeyUrl();
                }

                FileLogUtils.write(keyType + ":" + url);

                LogUtil.i(TAG, "keyType:"+url);

                httpUtils.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {

                    public void onFailure(HttpException a, String respose) {
                        LogUtil.i(TAG, "onFailure: 获取动态key失败");
                    }

                    public void onSuccess(ResponseInfo<String> respose) {
                        FileLogUtils.write(keyType + "_Result:" + respose.result);
                        if(TextUtils.isEmpty(respose.result))
                        {
                            Log.e("chengwenqiang","onFailure: result is null");
                            return;
                        }
                        LogUtil.i(TAG, "获取动态key成功onSuccess: " + respose.result);
                        try {
                            jsonrespose = new JSONObject(respose.result);
                            if(keyType.equals("CHANNELKEY")){
                                channelkey = jsonrespose.getString("ChannelKey");
                                LogUtil.i(TAG, "ChannelKey: " + channelkey);
                                Message msg = Message.obtain();
                                msg.what = GETCHANNELKEYSUC;
                                mClockHandler.sendMessage(msg);
                            }else if (keyType.equals("RECORDKEY")) {
                                String recordkey = jsonrespose.getString("RecordKey");
                                Message recordMsg = Message.obtain();
                                recordMsg.obj = recordkey;
                                recordMsg.what = GETRECORDKEYSUC;
                                mClockHandler.sendMessage(recordMsg);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }).start();
    }

    public void processSendChatMsg(){
        if (member_pressed) {
            mViewDialogue.setVisibility(View.GONE);
        }

        if (mEtBody.getText().toString().startsWith("</0")) {
            str = mEtBody.getText().toString();
        } else {

            str = mEtBody.getText().toString();

            if (str.length() == 0) {
                Toast.makeText(getApplicationContext(), getResources().getString(R.string.course_detail_msg_cant_be_null), Toast.LENGTH_SHORT).show();
                return;
            } else if (mRoomType == 3 && str.length() > 20) {
                Toast.makeText(getApplicationContext(), getResources().getString(R.string.course_detail_msg_cant_beyond_limit), Toast.LENGTH_SHORT).show();
                return;
            }

            String regex = ",|[.]|;|，|？|。|[?]|[\"]|[“”]|!|\\s+";
            String[] strAry = str.split(regex);
            String[] shieldWords = getResources().getStringArray(R.array.shield_words);

            if (isEnglishWords(str)) {
                for (String s : strAry) {
                    for (String shieldWord : shieldWords) {
                        if (s.equalsIgnoreCase(shieldWord)) {
                            Toast.makeText(getApplicationContext(), getResources().getString(R.string.course_detail_msg_with_sensitive_words), Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }
                }
            } else {
                for (String shieldWord : shieldWords) {
                    if (str.contains(shieldWord) || str.equalsIgnoreCase(shieldWord)) {
                        Toast.makeText(getApplicationContext(), getResources().getString(R.string.course_detail_msg_with_sensitive_words), Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
            }
        }

        if (!cutNet) {
            sendChatMsg(str);
        } else {
            Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_net_cannot_use), Toast.LENGTH_SHORT).show();
        }
    }

    public void sendChatMsg(String chatMsg){

        if (isLimitTalk) {
            Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_live_limit_send_msg), Toast.LENGTH_SHORT).show();
            return;
        }

        SimpleDateFormat objSDateFormat = new SimpleDateFormat("HH:mm:ss");// 转换为24小时制
        String strCurrentTime = objSDateFormat.format(new Date());

        if (mUserType == 4) {
            Pattern pattern= Pattern.compile("\\</\\d{3}/\\>");
            Matcher matcher = pattern.matcher(chatMsg);

            if (matcher.find()) {
                Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_cant_send_emoji_by_inspector), Toast.LENGTH_SHORT).show();
                return;
            } else {
                mUserName = "系统消息";
            }
        }

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("text", chatMsg);
        data.put("user", mUserName);
        data.put("time", strCurrentTime);
        data.put("usertype", mUserType);
        JSONObject bodystr = new JSONObject(data);
        Map<String, Object> data1 = new HashMap<String, Object>();
        data1.put("type", "chat");
        data1.put("body", bodystr);

        JSONObject object2 = new JSONObject(data1);

        Map<String, Object> data2 = new HashMap<String, Object>();
        data2.put("message", object2);
        final JSONObject msgJson = new JSONObject(data2);

        if (userlist.size() > 1) {
            LogUtil.i(TAG, "egine: " + egine);
            if(null==egine){
                return;
            }
            ThreadUtils.runOnSubThread(new Runnable() {
                @Override
                public void run() {
                    if (egine != null) {
                        egine.SendGroupMessage(Constant.CHATMSGTYPE, mGroup, msgJson.toString());
                        FileLogUtils.write("SendChatMsg: " + msgJson.toString());
                    }
                }
            });

            if (mChatMsgLists == null) {
                mChatMsgLists = new ArrayList<>();
            }
            mChatMsgLists.add(new VideoBody(mUserName, chatMsg, strCurrentTime, mUserType));
            if (member_pressed) {
                mIvMessage.setVisibility(View.VISIBLE);
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mChatHistoryAdapter.updateData(mChatMsgLists);
                        mLvChatMember.setSelection(mChatHistoryAdapter.getCount());// 选中最后一个listview的item
                    }
                });
            }

            mEtBody.setText("");
            str = null;
        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_cant_send_msg_without_users), Toast.LENGTH_SHORT).show();
                }
            });

        }
    }

    public static boolean isEnglishWords(String str) {
        String regex = ",|[.]|;|，|？|。|[?]|[\"]|[“”]|!|\\s+";
        String strAry[] = str.split(regex);
        for (int i = 0; i < strAry.length; i++) {
            for(int j=0; j< strAry[i].length(); j++){
                char ss = strAry[i].charAt(j);
                boolean s = String.valueOf(ss).matches("[^\\u4e00-\\u9fa5]");
                if(s){
                    Pattern pattern = Pattern.compile("[a-zA-Z]*");
                    Matcher isEnglish = pattern.matcher(strAry[i]);
                    if (!isEnglish.matches()) {
                        return false;
                    }
                }else{
                    return false;
                }
            }
        }
        return true;
    }

    /*播放视频流*/
    public void playVideoStream(String url){
        mFlVideoStreamShow.setVisibility(View.VISIBLE);
        mVideoStreamShow = true;
        mVideoTextureFragment = new VideoTextureFragment();
        Bundle bundle = new Bundle();
        bundle.putString("videopath", url);
        mVideoTextureFragment.setArguments(bundle);
        mFragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fl_video_stream_show, mVideoTextureFragment, "videoStream");
        fragmentTransaction.commit();

        mFlVideoStreamShow.setOnDragFrameLayoutClickListener(new OnDragFrameLayoutClickListener() {
            @Override
            public void onDragFrameLayoutClick(boolean bigWindow) {
                mVideoTextureFragment.mLlSwitch.setVisibility(bigWindow ? View.VISIBLE : View.GONE);
            }
        });
    }

    /*停止拉流播放*/
    public void stopVideoStream(){
        if (mVideoStreamShow) {
            mFlVideoStreamShow.setVisibility(View.GONE);
            if (mVideoTextureFragment != null) {
                mVideoTextureFragment.stopVideoStream();
                mVideoTextureFragment = null;
            }
            mFlVideoStreamShow.removeAllViews();
        }
    }

    /**
     * entry room
     */
    private void setupChannel() {
        LogUtil.i(TAG, "setupChannel——mRoomType = " + mRoomType);
        LogUtil.i(TAG, "mUserType——" + mUserType);

        //mVideoStreamPath = "http://rtmp.xx.com/xx/LiveStream.flv";
        //playVideoStream(mVideoStreamPath);
        //playVideoStream("http://baobab.wdjcdn.com/14564977406580.mp4");

        if (isTabDevice()) {
            //平板设备
            if (mUserID == mHostID) {
                mBtnWbRemarks.setVisibility(View.VISIBLE);
            }
        }

        if (mRoomType != 3) {
            if (mUserType == 3 || mUserType == 4) {
                rtcEngine.muteLocalVideoStream(true);
                rtcEngine.muteLocalAudioStream(true);
            } else {
                if (mUserID == mHostID) {
                    setupLocalVideo(mFlRemoteVideoViewContainer);
                } else {
                    setupLocalVideo(mFlLocalVideoViewContainer);
                }
            }
        }

        if (mUserID == mHostID || mUserType == 3 || mUserType == 2) {
            showOrHideMenu(false);
        } else {
            showOrHideMenu(true);
        }

        //设置老师视频码率
        if (mUserID == mHostID) {
            switch (mVideoProfileType) {
                case -1:
                    rtcEngine.setVideoProfile(Constants.VIDEO_PROFILE_240P, true);
                    break;
                case 20:
                    rtcEngine.setVideoProfile(Constants.VIDEO_PROFILE_240P, true);
                    break;
                case 40:
                    rtcEngine.setVideoProfile(Constants.VIDEO_PROFILE_480P, true);
                    break;
                case 50:
                    rtcEngine.setVideoProfile(Constants.VIDEO_PROFILE_720P, true);
                    break;
            }
        }

        switch (mRoomType) {
            case 1: // 一对一
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mRlVideoIndicator.setVisibility(View.VISIBLE);
                        dm_layout.setVisibility(View.GONE);
                        mImageRaiseHand.setVisibility(View.GONE);
                        mImageRaiseHand.setSelected(false);
                        if (mUserID == mHostID || mUserType == 2) {
                            frameLayoutMenu.setVisibility(View.VISIBLE);
                        } else {
                            frameLayoutMenu.setVisibility(View.GONE);
                        }
                    }
                });

                //设置学生视频码率
                if (mUserType == 2) {
                    rtcEngine.setVideoProfile(Constants.VIDEO_PROFILE_240P, true);
                }
                break;
            case 2: // 小班
                if (mUserID != mHostID) {
                    rtcEngine.muteLocalAudioStream(true);
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mRlVideoIndicator.setVisibility(View.VISIBLE);
                        dm_layout.setVisibility(View.VISIBLE);
                        mImageRaiseHand.setVisibility(View.GONE);
                        mImageRaiseHand.setSelected(false);
                        if (mUserID == mHostID || mUserType == 3 || mUserType == 2) {
                            frameLayoutMenu.setVisibility(View.VISIBLE);
                        } else {
                            frameLayoutMenu.setVisibility(View.GONE);
                        }

                        boolean isEnterRoomCloseGuide = (boolean) SharedPreferencesUtils.getParam(VideoActivity.this, Constant.ENTER_CLASSROOM_GUIDE, false);
                        mLlGuideView.setVisibility(isEnterRoomCloseGuide ? View.GONE : View.VISIBLE);
                    }
                });

                //设置学生视频码率
                if (mUserType == 2) {
                    rtcEngine.setVideoProfile(Constants.VIDEO_PROFILE_180P, true);
                }
                break;
            case 3: // 大班 \ 公开课
                rtcEngine.setChannelProfile(CHANNEL_PROFILE_LIVE_BROADCASTING);
                if (mUserID != mHostID) {
                    rtcEngine.setClientRole(2, "");
                } else {
                    rtcEngine.setClientRole(1, "");
                    mAnchor = true;
                    setupLocalVideo(mFlRemoteVideoViewContainer);
                }

                if (mUserID == mHostID || mUserType == 3) {
                    mImageRaiseHand.setVisibility(View.GONE);
                    frameLayoutMenu.setVisibility(View.VISIBLE);
                }else{
                    mImageRaiseHand.setVisibility(View.GONE);
                    mImageRaiseHand.setSelected(false);
                    frameLayoutMenu.setVisibility(View.GONE);
                }

                //rtcEngine.setVideoProfile(Constants.VIDEO_PROFILE_180P, true);
                break;

            default:
                break;
        }

        // 加入Agora讨论组，带mRoomID和userid
        rtcEngine.joinChannel(channelkey, mRoomID + "", "", mUserID);
        LogUtil.i(TAG, "···········joinChannel·········mRoomID  " + mRoomID + "userID  " + mUserID + "···········\n··········key:"+channelkey);

        //进入agora频道时的日志
        mAgoraLogPath = getApplicationContext().getExternalFilesDir("Log").toString() + "/agora.log";
        Log.i("chengwenqiang","agoraLogPath:"+mAgoraLogPath);
        File file = new File(getExternalFilesDir("Log").toString());
        if (!file.exists()) {
            file.mkdir();
        }
        File agoraLogFile = new File(mAgoraLogPath);
        if(agoraLogFile.exists()){
            agoraLogFile.delete();
        }

        rtcEngine.setLogFile(mAgoraLogPath);
    }

    public void uploadAgoraLog(){
        if (mAgoraLogPath != null && !TextUtils.isEmpty(mAgoraLogPath)) {
            final File agoraLogFile = new File(mAgoraLogPath);
            if (agoraLogFile.exists()) {
                ThreadUtils.runOnSubThread(new Runnable() {
                    @Override
                    public void run() {
                        logUpload("agora", agoraLogFile);
                    }
                });
            }
        }
    }

    /*日志上传*/
    private void logUpload(String key, final File agoraLogFile) {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        String time = format.format(new Date());
        String preCrashStr;

        if(Info.MECHANISM_ID.equals(Info.TestGroupAgencyID)){
            preCrashStr="-testgroup-";
        }else if(Info.MECHANISM_ID.equals(Info.TracyClassAgencyID)){
            preCrashStr="-tracy-";
        }else if(Info.MECHANISM_ID.equals(Info.TutorAgencyID)){
            preCrashStr="-tutor-";
        }else if(Info.MECHANISM_ID.equals(Info.EClassAgencyID)){
            preCrashStr="-eclassh-";
        }else if(Info.MECHANISM_ID.equals(Info.PublicAgencyID)){
            preCrashStr = "-public-";
        }else if(Info.MECHANISM_ID.equals(Info.TalkillaAgencyID)){
            preCrashStr = "-talkilla-";
        }else if(Info.MECHANISM_ID.equals(Info.FeiboAgencyID)){
            preCrashStr = "-feibo-";
        }else {
            preCrashStr = "-public-";
        }

        VerificationKeyUtils keyUtils = new VerificationKeyUtils();
        String verificationKey = keyUtils.getVerificationKey(Info.MECHANISM_ID);

        params.addBodyParameter("Version", Info.APIVERSION);
        params.addBodyParameter("UA", "Android");
        params.addBodyParameter("Source", "Android");
        params.addBodyParameter("GroupID", Info.MECHANISM_ID);
        params.addBodyParameter("UserID", mUserName);
        params.addBodyParameter("VerificationKey", verificationKey);

        params.addBodyParameter("FileStream", agoraLogFile);

        String fileName = time + preCrashStr + key + "-" + mUserName + "-" + mUserID + ".log";
        params.addBodyParameter("FileName",fileName);

        httpUtils.send(HttpRequest.HttpMethod.POST, Constant.getLogUploadUrl(), params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                LogUtil.i(TAG,responseInfo.result);
                try {
                    JSONObject json = new JSONObject(responseInfo.result);
                    String result = json.getString("Result");

                    if("true".equals(result)){//上传成功
                        LogUtil.e("agoralog", "agoralog上传成功");
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
            }
        });
    }

    private void initView() {
        if(isTabDevice()){
            //平板设备
            mIvCommonWord = (ImageView) findViewById(R.id.iv_common_word);
            mBtnWbRefresh = (Button) findViewById(R.id.btn_wb_refresh);
            mBtnWbRemarks = (Button) findViewById(R.id.btn_wb_remarks);
            mFlRemarks = (FrameLayout) findViewById(R.id.fl_remarks);
            mTvRemarksContent = (TextView) findViewById(R.id.tv_remarks_content);
        }

        all_view = (LinearLayout) findViewById(R.id.all_view);

        mLlGuideView = (LinearLayout) findViewById(R.id.ll_guide_view);
        mIvGuideClose = (ImageView) findViewById(R.id.iv_guide_close);

        mRlVideoIndicator = (RelativeLayout) findViewById(R.id.rl_video_indicator);
        mLlVideoIndicator = (LinearLayout) findViewById(R.id.ll_video_indicator);
        mTvNameIndicator = (TextView) findViewById(R.id.tv_name_indicator);

        mLlLocalVideoContainer = (LinearLayout) findViewById(R.id.ll_local_video_container);
        mFlLocalVideoViewContainer = (FrameLayout) findViewById(R.id.fl_local_video_view_container);
        mLlRemoteVideoContainer = (LinearLayout) findViewById(R.id.ll_remote_video_container);
        mFlRemoteVideoViewContainer = (FrameLayout) findViewById(R.id.fl_remote_video_view_container);
        mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
        mClearEditText = (ClearEditText) findViewById(R.id.filter_edit);

        mFrescoGif = (SimpleDraweeView) findViewById(R.id.fresco_gif);

        ll_whiteboard = (FrameLayout) findViewById(R.id.ll_whiteboard);
        ll_divide = (LinearLayout) findViewById(R.id.ll_divide);
        frameLayout = (FrameLayout) findViewById(R.id.image_White_Board);

        mFlVideoStreamShow = (DragFrameLayout) findViewById(R.id.fl_video_stream_show);

        mSwipeRefreshChat = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_chat);
        mLvChatMember = (ListView) findViewById(R.id.lv_chat_member);
        mLvMember = (ListView) findViewById(R.id.lv_member);

        mEtBody = (EditText) findViewById(R.id.et_body);
        mEtBody.setFocusable(false);

        mIvEmoji = (ImageView) findViewById(R.id.iv_emoji);
        mArrowLeft = (ImageView) findViewById(R.id.arrow_left);
        mArrowRight = (ImageView) findViewById(R.id.arrow_right);
        tv_name = (TextView) findViewById(R.id.tv_name);
        mBtnSend = (Button) findViewById(R.id.btn_send);
        dm_layout = (LinearLayout) findViewById(R.id.dm_layout);

        mRlDialogue = (RelativeLayout) findViewById(R.id.rl_dialogue);
        mRlMember = (RelativeLayout) findViewById(R.id.rl_member);
        mTvMemberNumber = (TextView) findViewById(R.id.tv_member_number);
        mViewDialogue = findViewById(R.id.view_dialogue);
        mViewMember = findViewById(R.id.view_member);
        mIvMessage = (ImageView) findViewById(R.id.iv_message);

        mFrameLayout = (FrameLayout) findViewById(R.id.graffiti_container);
        mWebView = (DrawableWebView) findViewById(R.id.webview);

        ll_below_video = (LinearLayout) findViewById(R.id.ll_below_video);
        mLlView = (LinearLayout) findViewById(R.id.ll_view);
        mPageText = (TextView) findViewById(R.id.pageText);

        mImageRaiseHand = (ImageView) findViewById(R.id.raise_hand);
        mTimerView = (TimerView) findViewById(R.id.timerView);

        mLlMusic = (LinearLayout) findViewById(R.id.ll_music);
        mRlMusic = (RelativeLayout) findViewById(R.id.rl_music);
        mTvMusicCurrentTime = (TextView) findViewById(R.id.tv_music_current_time);
        mTvMusicDuration = (TextView) findViewById(R.id.tv_music_duration);
        mSpbMusic = (ShaderProgressBar) findViewById(R.id.spb_music);

        mTvMusicName = (TextView) findViewById(R.id.tv_music_name);

        mLlMusicControl = (LinearLayout) findViewById(R.id.ll_music_control);
        mIvMusicPlayOrPause = (ImageView) findViewById(R.id.iv_music_play_pause);
        mIvMusicStop = (ImageView) findViewById(R.id.iv_music_stop);

        WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        mScreenWidth = display.getWidth();
        mScreenHeight = display.getHeight();

        int videoHeight = 0;
        if (isTabDevice()) {
            videoHeight = (int) ((mScreenHeight * 3.0 / 5.0) / 2.0);
            mRemoteVideoContainerWidth = (int) (videoHeight * 4.0 / 3.0);
        } else {
            mRemoteVideoContainerWidth = (int) (mScreenWidth * 1.0 / 4.0);
            videoHeight = (int) (mRemoteVideoContainerWidth * 3.0 / 4.0);
        }

        LayoutParams leftParams = mLlView.getLayoutParams();
        leftParams.width = mRemoteVideoContainerWidth;

        mLlView.setLayoutParams(leftParams);
        mLlView.invalidate();

        LayoutParams layoutParams = mLlRemoteVideoContainer.getLayoutParams();
        layoutParams.height = videoHeight;
        layoutParams.width = mRemoteVideoContainerWidth;

        mLlRemoteVideoContainer.setLayoutParams(layoutParams);
        mLlRemoteVideoContainer.invalidate();

        LayoutParams layoutParams1 = mLlLocalVideoContainer.getLayoutParams();
        layoutParams1.height = videoHeight;
        layoutParams1.width = mRemoteVideoContainerWidth;

        mLlLocalVideoContainer.setLayoutParams(layoutParams1);
        mLlLocalVideoContainer.invalidate();

        LayoutParams layoutParams2 = mRlVideoIndicator.getLayoutParams();
        layoutParams2.height = videoHeight;
        layoutParams2.width = mRemoteVideoContainerWidth;

        mRlVideoIndicator.setLayoutParams(layoutParams2);
        mRlVideoIndicator.invalidate();

        mLlLocalVideoContainer.measure(View.MeasureSpec.EXACTLY, View.MeasureSpec.EXACTLY);

        initHistoryChat();

        enableWebMode();
    }

    public void enableWebMode(){
        try {
            final WebSettings webSettings = mWebView.getSettings();

            //设置与JS的交互
            webSettings.setJavaScriptEnabled(true);

            //支持通过JS打开新的窗口
            webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

            webSettings.setSupportZoom(false);//支持缩放
            webSettings.setBuiltInZoomControls(true);//设置内置的缩放控件
            webSettings.setDisplayZoomControls(false);//隐藏自带的缩放控件

            //webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                webSettings.setMediaPlaybackRequiresUserGesture(false);
            }

            webSettings.setUseWideViewPort(true);

            webSettings.setLoadWithOverviewMode(true);//设置webview加载的页面的模式
            webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);

            mWebView.setInitialScale(1);

            mWebView.setWebViewClient(new WebViewClient(){
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    Log.e("url", url);
                    if(url.startsWith("intent")){
                        return true;
                    }else{
                        return super.shouldOverrideUrlLoading(view, url);
                    }
                }
            });

            //web控件点击弹出或隐藏工具栏
            mWebView.setOnWebClickListener(new OnWebClickListener() {
                @Override
                public void onWebClick() {
                    long currentTimeMillis = System.currentTimeMillis();

                    if(currentTimeMillis - mLastWebClickTime < 200){
                        setAnimatorSet();
                    }
                    mLastWebClickTime = currentTimeMillis;
                }
            });

            //划线数据监听
            mWebView.setOnDrawTouchListener(new OnDrawTouchListener() {
                @Override
                public void onDrawData(GraffitiInfo.GraffitiPageBean.GraffitiDataBean graffitiDataBean) {
                    AddGraffitiBean addGraffitiBean = new AddGraffitiBean();
                    AddGraffitiBean.MessageBean messageBean = new AddGraffitiBean.MessageBean();
                    AddGraffitiBean.MessageBean.WhiteboardBean whiteboardBean = new AddGraffitiBean.MessageBean.WhiteboardBean();
                    whiteboardBean.setCurrentpage(currentPage);
                    whiteboardBean.setFileid(mFileID);
                    whiteboardBean.setObjid(graffitiDataBean.getGraffitiId());
                    whiteboardBean.setColour("0XFF9000");
                    whiteboardBean.setObjtype("pen");
                    whiteboardBean.setObjdata(graffitiDataBean.getCoordinates());
                    whiteboardBean.setSubcommand("addgraffiti");
                    messageBean.setType("whiteboard");
                    messageBean.setWhiteboard(whiteboardBean);
                    addGraffitiBean.setMessage(messageBean);
                    final String jsonString = new Gson().toJson(addGraffitiBean);
                    LogUtil.e("webgraffiti", jsonString);
                    ThreadUtils.runOnSubThread(new Runnable() {
                        @Override
                        public void run() {
                            if (mUserID == mHostID || currentPage == mTeacherCurrentPage) {
                                if (egine != null) {
                                    egine.SendGroupMessage(Constant.WHITEBOARDMSGTYPE, mGroup, jsonString);
                                }
                            }
                        }
                    });
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void initHistoryChat() {
        mSwipeRefreshChat.setColorSchemeResources(android.R.color.holo_orange_light,
                                                  android.R.color.holo_blue_bright,
                                                  android.R.color.holo_green_light,
                                                  android.R.color.holo_red_light);

        mSwipeRefreshChat.setDistanceToTriggerSync(30);

        if(!mSwipeRefreshChat.isRefreshing()){
            mSwipeRefreshChat.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    getHistoryChatData(1, 20);
                }
            });
        }

        View headerView = LayoutInflater.from(this).inflate(R.layout.item_chat_headerview, null);
        mTvLoadHistoryChat = (TextView) headerView.findViewById(R.id.tv_load_history_chat);
        mPbLoadHistoryChat = (ProgressBar) headerView.findViewById(R.id.pb_load_history_chat);
        mTvLoadHistoryChat.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                mTvLoadHistoryChat.setVisibility(View.GONE);
                mPbLoadHistoryChat.setVisibility(View.VISIBLE);

                getHistoryChatData(0, 20);
            }
        });
        mLvChatMember.addHeaderView(headerView);
        mChatHistoryAdapter = new ChatHistoryAdapter(VideoActivity.this, mChatMsgLists);
        mLvChatMember.setAdapter(mChatHistoryAdapter);
        mLvChatMember.setSelection(mChatHistoryAdapter.getCount());
    }

    private void getHistoryChatData(final int chatmethod, final int chatNums) {

        HttpUtils httpUtils = new HttpUtils();

        RequestParams params = new RequestParams();

        VerificationKeyUtils keyUtils = new VerificationKeyUtils();
        String verificationKey = keyUtils.getVerificationKey(Info.MECHANISM_ID);

        params.addBodyParameter("Version", Info.APIVERSION);
        params.addBodyParameter("RoomID", mRoomID + "");
        params.addBodyParameter("UserID", mUserID + "");
        params.addBodyParameter("PageNow", ++mHistoryChatPage + "");
        params.addBodyParameter("PageSize", chatNums + "");
        params.addBodyParameter("VerificationKey", verificationKey);

        FileLogUtils.write("getDocServerURL:" + Constant.getIMChatHistoryUrl());
        httpUtils.send(HttpRequest.HttpMethod.POST, Constant.getIMChatHistoryUrl(), params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                FileLogUtils.write("getchathistory:" + responseInfo.result);
                IMHistoryInfoBean imHistoryInfoBean = mGson.fromJson(responseInfo.result, IMHistoryInfoBean.class);
                if (imHistoryInfoBean.isResult()) {
                    List<IMHistoryInfoBean.MessageBean> messageBean = imHistoryInfoBean.getMessage();

                    getIMChatHistorySuccess(chatmethod, messageBean, chatNums);
                } else {
                    getIMChatHistoryFailed(chatmethod, imHistoryInfoBean.getCode());
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                e.printStackTrace();
                getIMChatHistoryFailed(chatmethod, s);
            }
        });
    }

    private void getIMChatHistoryFailed(final int chatmethod, String error) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (chatmethod == 0) {
                    mTvLoadHistoryChat.setVisibility(View.VISIBLE);
                    mPbLoadHistoryChat.setVisibility(View.GONE);
                } else if (chatmethod == 1) {
                    if (mSwipeRefreshChat.isRefreshing()) {
                        mSwipeRefreshChat.setRefreshing(false);
                    }
                }
            }
        });
    }

    private void getIMChatHistorySuccess(final int chatmethod, List<IMHistoryInfoBean.MessageBean> messageBean,
                                         int chatNums) {
        if (mChatMsgLists == null) {
            mChatMsgLists = new ArrayList<>();
        }

        try {
            mNoMoreChatHistory = messageBean.size() < chatNums ? true : false;

            for (IMHistoryInfoBean.MessageBean bean : messageBean) {
                VideoBody chatMsgBean = new VideoBody();
                String chatMsgText = new String(Base64.decode(bean.getMessageText(), Base64.DEFAULT), "utf-8").trim();

                HistoryChatMsgBean historyChatMsgBean = mGson.fromJson(chatMsgText, HistoryChatMsgBean.class);

                chatMsgBean.setTime(historyChatMsgBean.getMessage().getBody().getTime());
                chatMsgBean.setUser(historyChatMsgBean.getMessage().getBody().getUser());
                chatMsgBean.setText(historyChatMsgBean.getMessage().getBody().getText());
                chatMsgBean.setUsertype(historyChatMsgBean.getMessage().getBody().getUsertype());
                mChatMsgLists.add(0, chatMsgBean);
            }

            final int scrollToPosition = messageBean.size();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    if (chatmethod == 0) {
                        mTvLoadHistoryChat.setVisibility(View.VISIBLE);
                        mPbLoadHistoryChat.setVisibility(View.GONE);
                    } else if (chatmethod == 1) {
                        if (mSwipeRefreshChat.isRefreshing()) {
                            mSwipeRefreshChat.setRefreshing(false);
                        }
                    }

                    mChatHistoryAdapter.updateData(mChatMsgLists);
                    mLvChatMember.setSelection(scrollToPosition);

                    if (mNoMoreChatHistory) {
                        mSwipeRefreshChat.setEnabled(false);
                        mTvLoadHistoryChat.setVisibility(View.GONE);
                    } else {
                        mSwipeRefreshChat.setEnabled(true);
                        mTvLoadHistoryChat.setVisibility(View.VISIBLE);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            getIMChatHistoryFailed(chatmethod, e.getMessage());
        }
    }

    /***
     * 创建rtcEngine实例
     */
    private void setupRtcEngine() {
        ((TalkApplication) getApplication()).setRtcEngine(Info.APP_KEY);
        rtcEngine = ((TalkApplication) getApplication()).getRtcEngine();
        ((TalkApplication) getApplication()).setEngineEventHandlerActivity(this);

        if (rtcEngine != null) {
            //rtcEngine.setLogFile(getApplicationContext().getExternalFilesDir("Log").toString() + "/agorasdk.log");
            rtcEngine.enableVideo();
        }
    }

    private void setupUriRtcEngine() {
        LogUtil.i(TAG, "创建rtcEngine实例");
        MessageHandler messageHandler = new MessageHandler();
        messageHandler.setActivity(this);
        try {
            rtcEngine = (RtcEngineEx) RtcEngineEx.create(this, Info.APP_KEY, messageHandler);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //rtcEngine.setLogFile(getApplicationContext().getExternalFilesDir("Log").toString() + "/agorasdk.log");
        rtcEngine.enableVideo();
    }

    // 离开视频聊天
    @Override
    public void onBackPressed() {
        LogUtil.i(TAG, "onBackPressed");

        try {
            ThreadUtils.runOnSubThread(new Runnable() {
                @Override
                public void run() {
                    if (egine != null) {
                        egine.LeaveGroup(mGroup);
                        egine.UnRegister();
                        egine = null;
                    }
                }
            });

            musicRelease();

            if (mUserID == mHostID) {
                stopRecording();
            }

            if (rtcEngine != null) {
                rtcEngine.leaveChannel();
                rtcEngine.destroy();
                rtcEngine = null;
            }
            finish();
            if(isVoucherJump) {
                System.exit(0);
            }

            super.onBackPressed();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    // 加入频道成功
    @SuppressLint("SimpleDateFormat")
    public void onJoinChannelSuccess(String channel, final int uid, int elapsed) {
        Log.i("chengwenqiang","chengwenqiang onJoinChannelSuccess");
        mUserID = uid;

        String recordValue = new SimpleDateFormat("yyyy-MM-dd/HH:mm:ss").format(Calendar.getInstance().getTime());

        String recordUrl = rtcEngine.makeQualityReportUrl(channel, uid, 0, 0);
    }

    /***
     * @param uid
     * @param width
     * @param height
     * @param elapsed 远程用户视频第一次解码回调
     */
    public synchronized void onFirstRemoteVideoDecoded(final int uid, int width, int height, final int elapsed) {

        LogUtil.d(TAG, "远程用户视频第一次解码回调uid_" + uid);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mRoomType == 3) {
                    mRemoteStreamUid = uid;
                    setupRemoteVideo(uid);
                }else {
                    if (uid == mHostID) {
                        mRemoteStreamUid = uid;
                        setupRemoteVideo(uid);
                    }else{
                        if(mUserType != 2 && mUserIdLists.size() > 0){
                            //setupVideoStream(Integer.parseInt(mUserIdLists.get(0)), mLocalVideoViewContainer);
                            if (mUserType == 2 && mCurrentMultiVideoNum == 0) {
                                setupLocalVideo(mFlLocalVideoViewContainer);
                            } else {
                                if (mUserIdLists.size() > 0) {
                                    mCurrentMultiVideoNum = mCurrentMultiVideoNum < 0 ? 0 : mCurrentMultiVideoNum;
                                    setupVideoStream(Integer.parseInt(mUserIdLists.get(mCurrentMultiVideoNum)), mFlLocalVideoViewContainer);
                                }
                            }
                        }
                    }
                }
            }
        });
    }

    @Override
    public void onFirstRemoteVideoFrame(int uid, int width, int height, int elapsed) {
        super.onFirstRemoteVideoFrame(uid, width, height, elapsed);
    }

    private void setupLocalVideo(FrameLayout container) {
        if (container.getChildCount() >= 1) {
            container.removeAllViews();
        }
        SurfaceView surfaceView = RtcEngine.CreateRendererView(getBaseContext());
        surfaceView.setZOrderMediaOverlay(true);
        rtcEngine.setVideoProfile(Constants.VIDEO_PROFILE_240P, true);
        container.addView(surfaceView);
        rtcEngine.setupLocalVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, 0));
    }

    private void setupVideoStream(int uid, FrameLayout container) {
        if (container.getChildCount() >= 1) {
            container.removeAllViews();
        }

        SurfaceView surfaceView = RtcEngine.CreateRendererView(getBaseContext());

        surfaceView.setZOrderMediaOverlay(true);

        container.addView(surfaceView);
        if (rtcEngine != null) {
            rtcEngine.setupRemoteVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, uid));
        }

        surfaceView.setTag(uid);
    }

    private void setupRemoteVideo(int uid, String type) {
        FrameLayout container = null;
        if (type != null) {
            container = (FrameLayout) findViewById(R.id.fl_local_video_view_container);
            localMainViewFlag = true;
        }else{
            container = (FrameLayout) findViewById(R.id.fl_remote_video_view_container);
            localMainViewFlag = false;
        }

        if (container.getChildCount() >= 1) {
            container.removeAllViews();
        }

        SurfaceView surfaceView = RtcEngine.CreateRendererView(getBaseContext());
        surfaceView.setZOrderMediaOverlay(true);
        container.addView(surfaceView);
        rtcEngine.setupRemoteVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, uid));

        surfaceView.setTag(uid);
    }

    private void setupRemoteVideo(int uid) {
        setupRemoteVideo(uid, null);
    }

    public synchronized void onUserJoined(final int uid, int elapsed) {
        LogUtil.d(TAG, "Agora_onUserJoined用户加入房间uid" + uid + "Agora什么都没做，換成IM来实现这部分的功能");
    }

    // 其他用户离开频道
    public void onUserOffline(final int uid) {

        if (uid == mHostID) {
            mFlRemoteVideoViewContainer.removeAllViews();
            mLlRemoteVideoContainer.setBackgroundResource(R.drawable.defautteacherimage);
        }
        LogUtil.d(TAG, "Agora_onUserOffline用户离开房间");
    }

    @Override
    public void onLeaveChannel(IRtcEngineEventHandler.RtcStats stats) {
        super.onLeaveChannel(stats);
        rtcEngine.stopPreview();
    }

    //监听其他用户是否关闭视频
    public void onUserMuteVideo(final int uid, final boolean muted) {
    }

    //监听其他用户是否关闭音频
    public void onUserMuteAudio(int uid, boolean muted) {
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.start();
    }

    @Override
    public void OnJoinGroup(Integer errcode, String group, String userList) {
        mGroup = group;
        userlist = new ArrayList<>();
        mOperationMenuBeanList = new ArrayList<>();
        if (errcode == -414) {
            showLockAccount();
        } else {
            if (isIMReconnect) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_user_enter), Toast.LENGTH_SHORT).show();
                    }
                });

                if(mRoomType != 3 && mUserType != 3 && mUserType != 4){
                    doReconnectIM();
                } else if (mRoomType == 3) {
                    if (mUserID == mHostID) {
                        doReconnectIM();
                    }
                }
            }

            LogUtil.i(TAG, "OnJoinGroup: 群组成员userList" + userList);
            // 成功加入群组
            try {
                JSONObject userlistjson = new JSONObject(userList);

                String list = userlistjson.getString("list");

                JSONArray jsonArray = new JSONArray(list);

                for (int i = 0; i < jsonArray.length(); i++) {

                    MemberItemInfo memberItemInfo = mGson.fromJson(jsonArray.get(i).toString(), MemberItemInfo.class);
                    if (memberItemInfo.getType() != 4) {
                        if (memberItemInfo.getType() == 1) {
                            userlist.add(0, memberItemInfo);//把老师的位置放在第一
                            //获取到老师账号account
                            hostAccount = userlist.get(0).getAccount();
                        } else {
                            userlist.add(memberItemInfo);
                        }
                        LogUtil.i(TAG, "OnJoinGroup: userlist" + userlist.size());
                    }

                    if (mUserType == 4 && Integer.parseInt(memberItemInfo.getUserid()) == mUserID) {
                        userlist.add(memberItemInfo);
                    }

                    LogUtil.i(TAG, "OnJoinGroup: userlist" + userlist.size());

                    mOperationMenuBeanList.add(new OperationMenuBean(memberItemInfo.getUserid(), false, true, false, true));

                    mUserIdLists = new ArrayList<>();

                    if (userlist != null) {
                        for (MemberItemInfo memberItemInfo1 : userlist) {
                            if (memberItemInfo1.getType() == 2) {
                                if(memberItemInfo1.getUserid().equals(mUserID + "")){
                                    mUserIdLists.add(0, mUserID + "");
                                }else {
                                    mUserIdLists.add(memberItemInfo1.getUserid());
                                }
                            }
                        }
                    }

                    drawIndicator(mCurrentMultiVideoNum, mUserIdLists.size());
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mRoomType == 3) {
                            mMemberNumber = userlist.size();
                            mTvMemberNumber.setText(getString(R.string.course_detail_member) + "(" + mMemberNumber + ")");
                        }
                    }
                });

            } catch (JSONException e) {
                e.printStackTrace();
            }

            if (mUserID == mHostID && userlist.size() > 1) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (isWebMode) {
                            LogUtil.e("webUrl", fileDir);
                            switchAndShareWeb(mFileID, fileDir, FileInfo_list.get(0).getFileName());
                        } else {
                            upLoadCurrentTextBook(fileDir, currentPage);
                        }
                    }
                });
            }

            if (mRoomType == 1) {
                if (mUserType == 2 && userlist.size() > 1) {
                    getChannelKey(mRoomID + "", mUserID + "", "RECORDKEY");
                }

                if (mUserID == mHostID && userlist.size() > 1) {

                    if (!isIMReconnect) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                SendClockMessage.sendMessge(mGroup, 0);
                            }
                        });

                        ClockBean clockBean = new ClockBean();
                        clockBean.setType("timer");
                        clockBean.setSubcommand("start");

                        setTimerDate(clockBean);
                    }

                    getChannelKey(mRoomID + "", mUserID + "", "RECORDKEY");
                }
            }
        }
    }

    /*绘制视频指示器*/
    private void drawIndicator(final int currentMultiVideoNum, final int size) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mLlVideoIndicator.removeAllViews();
                mTvNameIndicator.setVisibility(View.GONE);
                String userName = "";
                if (size > 1 && mRoomType == 2) {
                    mTvNameIndicator.setVisibility(View.VISIBLE);
                    if (mUserType == 2 && mCurrentMultiVideoNum == 0) {
                        userName = "";
                    } else {
                        for (MemberItemInfo listBean : userlist) {
                            if (listBean.getUserid().equals(mUserIdLists.get(mCurrentMultiVideoNum)))
                            {
                                userName = listBean.getUsername();
                            }
                        }
                    }

                    mTvNameIndicator.setText(userName);

                    for (int i = 0; i < size; i++) {
                        ImageView imageView = new ImageView(VideoActivity.this);
                        int width = DensityUtil.dip2px(VideoActivity.this, 5);
                        int heigth = DensityUtil.dip2px(VideoActivity.this, 5);
                        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, heigth);
                        params.leftMargin = DensityUtil.dip2px(VideoActivity.this, 5);

                        if (i == currentMultiVideoNum) {
                            imageView.setImageResource(R.drawable.shape_indicator_blue);
                        }else {
                            imageView.setImageResource(R.drawable.shape_indicator_gray);
                        }

                        mLlVideoIndicator.addView(imageView, params);
                    }
                }
            }
        });
    }

    public void OnGroupUserList(String gCode, String userList) {
        mGroup = gCode;
        userlist = new ArrayList<>();
        LogUtil.i(TAG, "OnJoinGroup: 群组成员userList" + userList);
        // 成功加入群组
        try {
            JSONObject userlistjson = new JSONObject(userList);

            String list = userlistjson.getString("list");

            JSONArray jsonArray = new JSONArray(list);

            for (int i = 0; i < jsonArray.length(); i++) {

                MemberItemInfo memberItemInfo = mGson.fromJson(jsonArray.get(i).toString(), MemberItemInfo.class);
                if (memberItemInfo.getType() != 4) {
                    if (memberItemInfo.getType() == 1) {
                        userlist.add(0, memberItemInfo);//把老师的位置放在第一
                    } else {
                        userlist.add(memberItemInfo);
                    }

                    LogUtil.i(TAG, "OnJoinGroup: userlist" + userlist.size());
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void OnRegister(final int userid, int errcode, String account) {
        if (errcode == -414) {
            showLockAccount();
        } else {
            final long currentTimeMillis = System.currentTimeMillis();
            final long enterTime = (long) SharedPreferencesUtils.getParam(VideoActivity.this, Constant.ENTER_CLASSROOM_TIME, Long.MIN_VALUE);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (currentTimeMillis - enterTime > 5 * 1000 && !isIMReconnect) {
                        Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_enter_course_success), Toast.LENGTH_SHORT).show();
                    }
                }
            });

            strAccount=account;

            mUserID = userid;
            LogUtil.i(TAG, "OnViewRegister: 注册成功回调---用户ID" + userid + "  userID=" + mUserID + "   account = "+account);

            if (errcode == 0) {
                ThreadUtils.runOnSubThread(new Runnable() {
                    @Override
                    public void run() {
                        egine.JoinGroup(mRoomID, "eclass", userid);
                    }
                });

                mUserAcount = account;
                getChannelKey(mRoomID + "", mUserID + "", "CHANNELKEY");
            }else {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        doRegister(mUserID, mUserName, mUserType);
                    }
                }).start();
            }
        }
    }

    /*IM账号锁定*/
    private void showLockAccount() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(!isAccountLocked){
                    isAccountLocked = !isAccountLocked;
                    AlertDialog alertDialog = new AlertDialog.Builder(VideoActivity.this)
                            .setTitle(getResources().getString(R.string.course_detail_account_be_locked))
                            .setIcon(android.R.drawable.ic_dialog_info)
                            .setPositiveButton(getResources().getString(R.string.course_sure), new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // 点击“确认”后的操作
                                    VideoActivity.this.finish();
                                }
                            }).show();

                    alertDialog.setCanceledOnTouchOutside(false);
                    alertDialog.setCancelable(false);
                    alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                        @Override
                        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                            if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0)
                            {
                                return true;
                            }

                            return false;
                        }
                    });
                }
            }
        });
    }

    @Override
    public void OnUserJoinGroup(String account, String name, int type) {
        LogUtil.i(TAG, "OnViewRegister: 加入群组成功回调");

        String a[] = account.split(":");

        uuid = Integer.parseInt(a[0]);

        JSONObject newuserjoinjson = new JSONObject();

        try {
            newuserjoinjson.put("account", account);
            newuserjoinjson.put("type", type);
            newuserjoinjson.put("userid", uuid);
            newuserjoinjson.put("username", name);
            newuserjoinjson.put("likenum", 0);

        } catch (JSONException e) {
            e.printStackTrace();
        }

        Gson gson = new Gson();
        LogUtil.i(TAG, "OnUserJoinGroup: newuserjoinjson" + newuserjoinjson.toString());

        MemberItemInfo newUserListBean = gson.fromJson(newuserjoinjson.toString(), MemberItemInfo.class);

        LogUtil.i(TAG, "newUserListBean.getUserid()" + newUserListBean.getUserid());

        for (int i = 0; i < userlist.size(); i++) {
            LogUtil.i(TAG, "userlist.size" + userlist.size());

            /*如果新加入的成员的id不为巡视员且不在userlist里边，就添加至userlist*/
            LogUtil.i(TAG, "OnUserJoinGroup: " + newUserListBean.getUserid() + "--" + newUserListBean.getType());
            LogUtil.i(TAG, "OnUserJoinGroup: userlist.get(i).getUserid()" + userlist.get(0).getUserid());

            //if (!userlist.get(i).getUserid().equals(newUserListBean.getUserid()) && (newUserListBean.getType() != 4)) {
            if (!userlist.get(i).getUserid().equals(newUserListBean.getUserid())) {
                mOperationMenuBeanList.add(new OperationMenuBean(newUserListBean.getUserid(), false, true, false, true));

                if (newUserListBean.getType() != 4) {
                    if (uuid == mHostID) {
                        userlist.add(0, newUserListBean);
                    } else {
                        userlist.add(newUserListBean);
                        if (newUserListBean.getType() == 2) {
                            mUserIdLists.add(newUserListBean.getUserid());
                        }
                    }
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mRoomType == 3) {
                            mTvMemberNumber.setText(getString(R.string.course_detail_member) + "(" + (++mMemberNumber) + ")");
                        }

                        drawIndicator(mCurrentMultiVideoNum, mUserIdLists.size());

                        if (member_pressed) {
                            mSourceDateList = SortUtils.filledData(mCharacterParser, userlist);
                            Collections.sort(mSourceDateList, mPinyinComparator);
                            mSortMemberAdapter.updateListView(mSourceDateList);
                        }
                    }
                });
                break;//如果此处不break，则会多次添加。
            }
        }

        if (uuid == mHostID) {
            SharedPreferencesUtils.setParam(VideoActivity.this, mHostID + "", account);

            long currentTimeMillis = System.currentTimeMillis();

            if (currentTimeMillis - mAnchorLeaveChannelTime < 25* 60 * 1000) {
                mClockHandler.removeCallbacks(mLeaveChannealRunnable);
            } else {
                rtcEngine.joinChannel(channelkey, mRoomID + "", "", mUserID);
            }

            if (mUserType == 2 && mRoomType == 1) {
                getChannelKey(mRoomID + "", mUserID + "", "RECORDKEY");

                if(currentTimeMillis - mAnchorLeaveChannelTime < 25 * 60 * 1000){
                    mClockHandler.removeCallbacks(mStopRecordRunnable);
                }
            }
        }

        if (mUserID == mHostID && !isIMReconnect) {

            String command;
            if (!isVideoMode) {
                command = "switchToAudio";
                SendMicVideoMessage.sendMessge(command, "yes", 0, mGroup);
            }

            if (mRoomType == 1) {
                SendClockMessage.sendMessge(mGroup, 0);

                ClockBean clockBean = new ClockBean();
                clockBean.setType("timer");
                clockBean.setSubcommand("start");

                setTimerDate(clockBean);

                getChannelKey(mRoomID + "", mUserID + "", "RECORDKEY");
            } else if (mRoomType == 3) {
                if (isLimitTalkAll) {
                    limitSpeak(isLimitTalkAll, -1);
                }
            }

        }

        if (mUserID == mHostID || mAnchor) {
            if (isWebMode) {
                String fileName = "";
                for (CatalogBean catalogList : mCatalogLists) {
                    if (mFileID == catalogList.getFileId()) {
                        fileName = catalogList.getFileName();
                    }
                }

                sendCurrentWeb(fileName);
            } else {
                upLoadCurrentTextBook(fileDir, currentPage);
            }
        }
    }

    private void sendCurrentWeb(final String fileName) {

        if (isZipTextBook) {
            OpenWebCommandBean.MessageBean.WhiteboardBean whiteboardBean = new OpenWebCommandBean.MessageBean.WhiteboardBean();
            whiteboardBean.setFileid(mFileID);
            whiteboardBean.setFiledir(fileDir);
            whiteboardBean.setFilename(fileName);
            whiteboardBean.setPagenum(mPageNums);
            whiteboardBean.setDocserver(Constant.getH5BASEURL());
            whiteboardBean.setCurrentaction(0);
            whiteboardBean.setCurrentpage(currentPage);
            whiteboardBean.setSubcommand("openweb");
            OpenWebCommandBean.MessageBean openWebMessageBean = new OpenWebCommandBean.MessageBean();
            openWebMessageBean.setType("whiteboard");
            openWebMessageBean.setWhiteboard(whiteboardBean);

            if (mUserID == mHostID || mAnchor) {
                OpenWebCommandBean openWebCommandBean = new OpenWebCommandBean();
                openWebCommandBean.setMessage(openWebMessageBean);
                final String jsonString = new Gson().toJson(openWebCommandBean);
                ThreadUtils.runOnSubThread(new Runnable() {
                    @Override
                    public void run() {
                        if (egine != null) {
                            egine.SendGroupMessage(Constant.WHITEBOARDMSGTYPE, mGroup, jsonString);
                        }
                    }
                });
            }
        } else {
            mWebView.post(new Runnable() {
                @RequiresApi(api = Build.VERSION_CODES.KITKAT)
                @Override
                public void run() {
                    mWebView.evaluateJavascript("javascript:Presentation.CurrentStatus()", new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String s) {
                            try {
                                JSONObject jsonObject = new JSONObject(s);
                                currentPage = jsonObject.getInt("slide");
                                int currentaction = jsonObject.getInt("step");
                                for (CatalogBean h5CatlogList : mCatalogLists) {
                                    if (mFileID == h5CatlogList.getFileId()) {
                                        if (h5CatlogList.getPageNums() != null) {
                                            mPageNums = Integer.parseInt(h5CatlogList.getPageNums());
                                        }
                                    }
                                }

                                OpenWebCommandBean.MessageBean.WhiteboardBean whiteboardBean = new OpenWebCommandBean.MessageBean.WhiteboardBean();
                                whiteboardBean.setFileid(mFileID);
                                whiteboardBean.setFiledir(fileDir);
                                whiteboardBean.setFilename(fileName);
                                whiteboardBean.setPagenum(mPageNums);
                                whiteboardBean.setDocserver(Constant.getH5BASEURL());
                                whiteboardBean.setCurrentaction(currentaction);
                                whiteboardBean.setCurrentpage(currentPage);
                                whiteboardBean.setSubcommand("openweb");
                                OpenWebCommandBean.MessageBean openWebMessageBean = new OpenWebCommandBean.MessageBean();
                                openWebMessageBean.setType("whiteboard");
                                openWebMessageBean.setWhiteboard(whiteboardBean);

                                if (mUserID == mHostID || mAnchor) {
                                    OpenWebCommandBean openWebCommandBean = new OpenWebCommandBean();
                                    openWebCommandBean.setMessage(openWebMessageBean);
                                    final String jsonString = new Gson().toJson(openWebCommandBean);
                                    ThreadUtils.runOnSubThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (egine != null) {
                                                egine.SendGroupMessage(Constant.WHITEBOARDMSGTYPE, mGroup, jsonString);
                                            }
                                        }
                                    });
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            });
        }
    }

    public Runnable mLeaveChannealRunnable = new Runnable() {
        @Override
        public void run() {
            if (rtcEngine != null) {
                rtcEngine.leaveChannel();

                mFlLocalVideoViewContainer.removeAllViews();
                mLlLocalVideoContainer.setBackgroundColor(Color.GRAY);
            }
        }
    };

    public Runnable mStopRecordRunnable = new Runnable() {
        @Override
        public void run() {
            if(rtcEngine != null){
                int stop = rtcEngine.stopRecordingService(mRecordKey);

                if (stop < 0) {
                    mClockHandler.postDelayed(mStopRecordRunnable, 60 * 1000);
                }

                stopRecording();
            }
        }
    };

    @Override
    public void OnUserLeaveGroup(final String account, final String name, final int type, final int leaveType) {
        LogUtil.e("leaveGroup", "account:" + account + ",name:" + name + ",leaveType:" + leaveType);
        String a[] = account.split(":");
        luuid = Integer.parseInt(a[0]);
        if (isOperationMenuDialog && mOperatedUserId != null && mOperatedUserId.equals(a[0])) {
            mOperationMenuDialog.dismiss();
            isOperationMenuDialog = false;
        }

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (leaveType != 1) {
                    if (mRoomType == 3) {
                        if (luuid == mHostID && mUserID != luuid) {
                            Toast.makeText(getApplicationContext(), name + getResources().getString(R.string.course_detail_net_reconnnect), Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        if (type != 4 && type != 3 && mUserID != luuid) {
                            Toast.makeText(getApplicationContext(), name + getResources().getString(R.string.course_detail_net_reconnnect), Toast.LENGTH_SHORT).show();
                        }
                    }
                }

                for (int i = 0; i < userlist.size(); i++) {
                    if (userlist.get(i).getUserid().equals(luuid + "")) {
                        userlist.remove(i);
                    }
                }
                for (int j = 0; j < mUserIdLists.size(); j++) {
                    if (mUserIdLists.get(j).equals(luuid + "")) {
                        mUserIdLists.remove(j);
                        if (mCurrentMultiVideoNum >= j) {
                            mCurrentMultiVideoNum--;
                        }
                    }
                }

                if (mRoomType == 3) {
                    //更新教室中人数
                    mTvMemberNumber.setText(getString(R.string.course_detail_member) + "(" + (--mMemberNumber) + ")");
                    if (luuid == mHostID && mUserID != luuid && leaveType == 1) {
                        Toast.makeText(getApplicationContext(), name + getResources().getString(R.string.course_detail_user_leave_room), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    if (type != 4 && type != 3 && mUserID != luuid && leaveType == 1) {
                        Toast.makeText(getApplicationContext(), name + getResources().getString(R.string.course_detail_user_leave_room), Toast.LENGTH_SHORT).show();
                    }
                }

                if (isVideoMode) {
                    if (mUserType == 2 && mCurrentMultiVideoNum == 0) {
                        setupLocalVideo(mFlLocalVideoViewContainer);
                    } else {
                        if (mUserIdLists.size() > 0) {
                            mCurrentMultiVideoNum = mCurrentMultiVideoNum < 0 ? 0 : mCurrentMultiVideoNum;
                            setupVideoStream(Integer.parseInt(mUserIdLists.get(mCurrentMultiVideoNum)), mFlLocalVideoViewContainer);
                        } else {
                            mFlLocalVideoViewContainer.removeAllViews();
                            mFlLocalVideoViewContainer.setBackgroundResource(R.drawable.defautteacherimage);
                        }
                    }

                    drawIndicator(mCurrentMultiVideoNum , mUserIdLists.size());
                }

                for (int j = 0; j < mOperationMenuBeanList.size(); j++) {
                    if (mOperationMenuBeanList.get(j).getUseId().equals(luuid + ""))
                    {
                        mOperationMenuBeanList.remove(j);
                    }
                }

                LogUtil.i(TAG, "userlist size" + userlist.size());

                if (luuid == mHostID) {
                    musicRelease();
                    mClockHandler.removeCallbacks(mRunnable);

                    IsPlaying = false;
                    mSpbMusic.setProgress(0);
                    mTvMusicCurrentTime.setText("00:00");
                    mTvMusicDuration.setText("00:00");

                    mFlRemoteVideoViewContainer.removeAllViews();
                    mFlRemoteVideoViewContainer.setBackgroundResource(isVideoMode ? R.drawable.defautteacherimage : R.drawable.max_audio_background);

                    mAnchorLeaveChannelTime = System.currentTimeMillis();

                    mClockHandler.postDelayed(mLeaveChannealRunnable, 25 * 60 * 1000);

                    if (mUserType == 2 && mRoomType == 1) {
                        mClockHandler.postDelayed(mStopRecordRunnable, 25 * 60 * 1000);
                    }

                    showOrHideMenu(mUserType == 3 || (mUserType == 2 && mRoomType != 3) ? false: true);
                    frameLayoutMenu.setVisibility(mUserType == 3 || (mUserType == 2 && mRoomType != 3) ? View.VISIBLE : View.GONE);
                }
                if (member_pressed) {
                    mSourceDateList = SortUtils.filledData(mCharacterParser, userlist);
                    Collections.sort(mSourceDateList, mPinyinComparator);
                    mSortMemberAdapter.updateListView(mSourceDateList);
                    mSortMemberAdapter.mAnchorID = mAnchorID;
                }
            }
        });
    }

    //用户在其他地方登记被迫下线
    @Override
    public void OnServerNotification(int errcode) {
        if (errcode == ConstantDefination.ERR_UID_RENEW) {
            LogUtil.i(TAG, "OnServerNotification: " + errcode + "用户在其他地方登记被迫下线");
            Looper.prepare();

            ThreadUtils.runOnSubThread(new Runnable() {
                @Override
                public void run() {
                    if(egine != null){
                    //egine.LeaveGroup(mGroup);
                    egine.UnRegister();
                    egine = null;
                    }
                }
            });

            if (rtcEngine != null) {
                rtcEngine.leaveChannel();
                rtcEngine = null;
            }
            musicRelease();

            try {
                AlertDialog alertDialog = new AlertDialog.Builder(VideoActivity.this)
                        .setTitle(getResources().getString(R.string.course_detail_quit_by_reuse))
                        .setIcon(android.R.drawable.ic_dialog_info)
                        .setPositiveButton(getResources().getString(R.string.course_sure), new DialogInterface.OnClickListener() {

                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               // 点击“确认”后的操作
                               ((TalkApplication) getApplication()).isAutoLogin(false);
                               SharedPreferences sp = getSharedPreferences("userpwd", Context.MODE_PRIVATE);

                               SharedPreferences.Editor editor = sp.edit();
                               editor.clear();
                               editor.commit();

                               VideoActivity.this.finish();
                               if (!isVoucherJump) {
                                   TalkApplication.destoryActivity("CourseInfoActivity");
                                   Intent intent = new Intent(VideoActivity.this, LoginActivity.class);
                                   startActivity(intent);
                               }else{
                                   System.exit(0);
                               }
                           }
                        }).show();

                alertDialog.setCanceledOnTouchOutside(false);
                alertDialog.setCancelable(false);
                alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                        if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0)
                        {
                            return true;
                        }

                        return false;
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }

            Looper.loop();
        }
    }

    public void OnConnectionError(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                doRegister(mUserID, mUserName, mUserType);
            }
        }).start();
    }

    @Override
    public void OnError(int errcode) {
        if (errcode == -404 || errcode == -405) {
            Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_im_disconnect), Toast.LENGTH_SHORT).show();
        } else if (errcode == -410) {
            Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_im_connect_timeout), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 接受命令是否锁定白板,　锁定就不显示悬浮菜单
     */
    private void showOrHideMenu(final boolean status) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (status) {
                    if (promotedActionsLibrary != null) {
                        promotedActionsLibrary.mainImageButton.setEnabled(false);

                        if (promotedActionsLibrary.meunEditButton.isSelected()) {
                            promotedActionsLibrary.meunEditButton.setSelected(false);
                            promotedActionsLibrary.meunEditButton.setImageDrawable(ContextCompat.getDrawable(
                                    getApplicationContext(), R.drawable.ic_menu_edit_uncheck));
                        }

                        if (mUserType != 3) {
                            promotedActionsLibrary.meunEditButton.setEnabled(false);
                            promotedActionsLibrary.menuCameraButton.setEnabled(false);
                        } else {
                            if (mRoomType != 1) {
                                promotedActionsLibrary.menuLimitAllButton.setEnabled(false);
                                promotedActionsLibrary.menuFileButton.setEnabled(false);
                            }
                        }

                        if (mUserID == mHostID) {
                            if (mRoomType == 1) {
                                promotedActionsLibrary.menuLockButton.setEnabled(false);
                            } else {
                                promotedActionsLibrary.menuLimitAllButton.setEnabled(false);
                            }
                            promotedActionsLibrary.menuFileButton.setEnabled(false);
                            promotedActionsLibrary.menuClearButton.setEnabled(false);

                            if (isTabDevice()) {
                                //平板设备
                                promotedActionsLibrary.menuRevokeButton.setEnabled(false);
                                promotedActionsLibrary.menuReveserRevocationButton.setEnabled(false);
                            }
                        }

                        if (promotedActionsLibrary.isMenuOpened) {
                            promotedActionsLibrary.closePromotedActions().start();
                            promotedActionsLibrary.isMenuOpened = false;
                        }

                        promotedActionsLibrary.mainImageButton.setImageDrawable(ContextCompat.getDrawable(
                                getApplicationContext(), R.drawable.ic_add_check));

                        mIsMovingPic = true;
                    }
                } else {
                    if (promotedActionsLibrary != null) {
                        promotedActionsLibrary.mainImageButton.setImageDrawable(ContextCompat.getDrawable(
                                getApplicationContext(), R.drawable.ic_add_check));
                        promotedActionsLibrary.mainImageButton.setEnabled(true);

                        if (mUserType != 3) {
                            promotedActionsLibrary.meunEditButton.setEnabled(true);
                            promotedActionsLibrary.menuCameraButton.setEnabled(true);
                        } else {
                            if(mRoomType != 1){
                                promotedActionsLibrary.menuLimitAllButton.setEnabled(true);
                                promotedActionsLibrary.menuFileButton.setEnabled(true);
                            }
                        }

                        if (mUserID == mHostID) {
                            if (mRoomType == 1) {
                                promotedActionsLibrary.menuLockButton.setEnabled(true);
                            } else{
                                promotedActionsLibrary.menuLimitAllButton.setEnabled(true);
                            }

                            promotedActionsLibrary.menuFileButton.setEnabled(true);
                            promotedActionsLibrary.menuClearButton.setEnabled(true);

                            if (isTabDevice()) {
                                //平板设备
                                promotedActionsLibrary.menuRevokeButton.setEnabled(true);
                                promotedActionsLibrary.menuReveserRevocationButton.setEnabled(true);
                            }
                        }

                        if (!promotedActionsLibrary.isMenuOpened) {
                            promotedActionsLibrary.openPromotedActions().start();
                            promotedActionsLibrary.isMenuOpened = true;
                        }

                        if ((mUserType == 2 && mAnchor) || mUserID == mHostID || mUserType == 3) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    promotedActionsLibrary.menuFileButton.setVisibility(View.VISIBLE);
                                }
                            });
                            promotedActionsLibrary.menuFileButton.setEnabled(true);
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    promotedActionsLibrary.menuFileButton.setVisibility(View.GONE);
                                }
                            });
                        }
                    }
                }
            }
        });
    }

    /**
     * 设置显示翻页图标
     */
    private void arrowShow() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (currentPage >= 1 && currentPage <= mPageNums) {
                    mArrowLeft.setVisibility(currentPage == 1 ? View.GONE : View.VISIBLE);
                    mArrowRight.setVisibility(currentPage == mPageNums ? View.GONE : View.VISIBLE);
                }
                mPageText.setText(currentPage + "/" + mPageNums);
            }
        });
    }

    /**
     * 悬浮菜单
     */
    private PromotedActionsLibrary promotedActionsLibrary;
    private FrameLayout            frameLayoutMenu;

    private void menu_5() {
        frameLayoutMenu = (FrameLayout) findViewById(R.id.container);
        promotedActionsLibrary = new PromotedActionsLibrary();
        promotedActionsLibrary.setup(getApplicationContext(), frameLayoutMenu);

        mOnPanelClickListener = new OnClickListener() {
            @Override
            public void onClick(View view) {
                FileUtils.verifyStoragePermissions(VideoActivity.this);//权限
                String tag = (String) view.getTag();

                if ((mUserID == mHostID || mUserType == 2) && mWhiteBoardBean == null) {
                    mWhiteBoardBean = new WhiteBoardBean();
                    mWhiteBoardBean.setCurrentpage(currentPage);
                    mWhiteBoardBean.setFileid(mFileID);
                    mWhiteBoardBean.setPagenum(mPageNums);
                    mWhiteBoardBean.setFilename(mFileName);
                    if (mGraffitiView != null) {
                        mGraffitiView.setWhiteBoardBeanInfo(mWhiteBoardBean);
                    }
                }

                if ("menu_edit".equals(tag)) {//画笔

                    /*if (null == mGraffitiView) {
                        return;
                    }*/

                    if (cutNet) {
                        Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_net_cannot_use), Toast.LENGTH_SHORT).show();
                        return;
                    }

                    mIsMovingPic = false;

                    if (!promotedActionsLibrary.meunEditButton.isSelected()) {
                        Toast.makeText(mContext, getResources().getString(R.string.course_detail_graffiti_enter_mode), Toast.LENGTH_SHORT).show();

                        promotedActionsLibrary.meunEditButton.setImageDrawable(ContextCompat.getDrawable(
                                getApplicationContext(), R.drawable.ic_menu_edit_check));
                        promotedActionsLibrary.meunEditButton.setSelected(true);

                        mWebView.setMode(DrawableWebView.Mode.DRAW);
                    } else {
                        Toast.makeText(mContext, getResources().getString(R.string.course_detail_graffiti_exit_mode), Toast.LENGTH_SHORT).show();

                        promotedActionsLibrary.meunEditButton.setImageDrawable(ContextCompat.getDrawable(
                                getApplicationContext(), R.drawable.ic_menu_edit_uncheck));
                        promotedActionsLibrary.meunEditButton.setSelected(false);

                        mWebView.setMode(DrawableWebView.Mode.SCALE);

                        mIsMovingPic = true;
                    }
                    if (mGraffitiView != null) {
                        mGraffitiView.setDrawShapeType();
                        mGraffitiView.setPaintSize(3);
                        mGraffitiView.setColor(Color.parseColor("#FF9000"), "0XFF9000");
                    }

                } else if ("menu_camera".equals(tag)) {//相机
                    if (cutNet) {
                        Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_net_cannot_use), Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (mGraffitiView != null) {
                        GraffitiPathPage graffitiPathPage = mGraffitiView.getGraffitiPathPage();
                        String fileid = graffitiPathPage.getFileid();
                        int currentPage = graffitiPathPage.getCurrentPage();
                        mGraffitiPathPageMap.put(fileid + "-" + String.valueOf(currentPage), graffitiPathPage);
                    }
                    showDailogcamera();
                }
                else if ("menu_lock".equals(tag)) {//解锁
                    if (cutNet) {
                        Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_net_cannot_use), Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (!promotedActionsLibrary.menuLockButton.isSelected()) {
                        promotedActionsLibrary.menuLockButton.setImageDrawable(ContextCompat.getDrawable(
                                getApplicationContext(), R.drawable.ic_menu_unlock));
                        promotedActionsLibrary.menuLockButton.setSelected(true);

                        unLockUser(true, 0);

                        Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_opretion_menu_unlock), Toast.LENGTH_SHORT).show();
                    } else {
                        promotedActionsLibrary.menuLockButton.setImageDrawable(ContextCompat.getDrawable(
                                getApplicationContext(), R.drawable.ic_menu_lock));
                        promotedActionsLibrary.menuLockButton.setSelected(false);

                        unLockUser(false, 0);

                        Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_opretion_menu_lock), Toast.LENGTH_SHORT).show();
                    }
                }
                else if ("menu_limitall".equals(tag)) {//禁言
                    if (cutNet) {
                        Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_net_cannot_use), Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (!promotedActionsLibrary.menuLimitAllButton.isSelected()) {
                        promotedActionsLibrary.menuLimitAllButton.setImageDrawable(ContextCompat.getDrawable(
                                getApplicationContext(), R.drawable.ic_menu_limittalk));
                        promotedActionsLibrary.menuLimitAllButton.setSelected(true);

                        limitSpeak(true, -1);
                        isLimitTalkAll = true;

                        for (OperationMenuBean operationMenuBean : mOperationMenuBeanList) {
                            operationMenuBean.setSpeakStatus(false);
                        }

                        Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_speak_limit_all), Toast.LENGTH_SHORT).show();
                    } else {
                        promotedActionsLibrary.menuLimitAllButton.setImageDrawable(ContextCompat.getDrawable(
                                getApplicationContext(), R.drawable.ic_menu_allowtalk));
                        promotedActionsLibrary.menuLimitAllButton.setSelected(false);

                        limitSpeak(false, -1);
                        isLimitTalkAll = false;

                        for (OperationMenuBean operationMenuBean : mOperationMenuBeanList) {
                            operationMenuBean.setSpeakStatus(true);
                        }

                        Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_speak_allow_all), Toast.LENGTH_SHORT).show();
                    }
                }
                else if ("menu_file".equals(tag)) {
                    if (cutNet) {
                        Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_net_cannot_use), Toast.LENGTH_SHORT).show();
                        return;
                    }

                    showFileDialog();
                }
                else if ("menu_clear".equals(tag)) {
                    if (cutNet) {
                        Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_net_cannot_use), Toast.LENGTH_SHORT).show();
                        return;
                    }

                    Toast.makeText(VideoActivity.this, getResources().getString(R.string.course_detail_graffiti_clear), Toast.LENGTH_SHORT).show();

                    SendClearGraffitoMessage.sendMessge(currentPage, mFileID, mPageNums, mGroup);

                    if (isWebMode) {
                        mWebView.clearGraffiti(mFileID, currentPage);
                    } else {
                        if (mGraffitiView != null) {
                            mGraffitiView.clearService();

                            String fileIdKey = mFileID + "-" + currentPage;
                            mGraffitiPaintData.remove(fileIdKey);
                            mGraffitiPathPageMap.remove(fileIdKey);
                        }
                    }
                }
                else if ("menu_revoke".equals(tag)) {
                    //Toast.makeText(ClassroomActivity.this, "撤销", Toast.LENGTH_SHORT).show();
                    if (isWebMode) {
                        int graffitiId = mWebView.revokeGraffiti();
                        if (graffitiId != 0) {
                            SendClearGraffitoMessage.revokeH5Graffiti(currentPage, mFileID, graffitiId, mGroup);
                        }
                    } else {
                        if (mGraffitiView.mPathStackBackup.size() > 0) {
                            GraffitiOrdermsgBean graffitiOrdermsgBean = mGraffitiView.mGraffitiOrderData.get(mGraffitiView.mPathStackBackup.size() - 1);
                            String objid = graffitiOrdermsgBean.getObjId();
                            LogUtil.e("revoke", "objectid:" + objid);
                            SendClearGraffitoMessage.revokeGraffiti(currentPage, mFileID, mPageNums, Integer.parseInt(objid), mGroup);
                            mGraffitiView.undoServer(objid);
                        }
                    }
                }
                else if ("menu_reverse_revocation".equals(tag)) {
                    //Toast.makeText(ClassroomActivity.this, "反撤销", Toast.LENGTH_SHORT).show();
                    if (isWebMode) {
                        AddGraffitiBean addGraffitiBean = mWebView.restoreGraffiti();
                        if (addGraffitiBean != null) {
                            final String jsonString = mGson.toJson(addGraffitiBean);
                            ThreadUtils.runOnSubThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (egine != null) {
                                        egine.SendGroupMessage(Constant.WHITEBOARDMSGTYPE, mGroup, jsonString);
                                    }
                                }
                            });
                        }
                    } else {
                        if ((mGraffitiView.mGraffitiOrderData.size() > 0) && (mGraffitiView.mGraffitiOrderData.size() > mGraffitiView.mPathStackBackup.size())) {
                            GraffitiOrdermsgBean graffitiOrdermsgBean = mGraffitiView.mGraffitiOrderData.get(mGraffitiView.mPathStackBackup.size());
                            final String message = graffitiOrdermsgBean.getOrderMsg();
                            ThreadUtils.runOnSubThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (egine != null) {
                                        egine.SendGroupMessage(Constant.WHITEBOARDMSGTYPE, mGroup, message);
                                    }
                                }
                            });

                            String type = graffitiOrdermsgBean.getType();
                            if (type.equals("L")) {
                                WhiteBoardBody whiteBoardBody = new Gson().fromJson(message, WhiteBoardBody.class);
                                WhiteBoardBean whiteBoardBean = mGraffitiView.getGraffitiLineData(whiteBoardBody);
                                doPaintGraffiti(whiteBoardBean);
                            } else if (type.equals("T")) {
                                TextWhiteBoardBean textWhiteBoardBean = new Gson().fromJson(message, TextWhiteBoardBean.class);
                                doPaintTextGraffiti(textWhiteBoardBean);
                            }
                        }
                    }
                }
            }
        };
        if (mUserID == mHostID) {
            if (isTabDevice()) {
                //平板设备
                promotedActionsLibrary.addItemReveserRevocation(
                        ContextCompat.getDrawable(getApplicationContext(),
                                                  R.drawable.selector_ic_menu_reverse_revocation), mOnPanelClickListener, "menu_reverse_revocation");
                promotedActionsLibrary.addItemRevoke(ContextCompat.getDrawable(getApplicationContext(),
                                                                               R.drawable.selector_ic_menu_revoke), mOnPanelClickListener, "menu_revoke");

                promotedActionsLibrary.menuRevokeButton.setEnabled(false);
                promotedActionsLibrary.menuReveserRevocationButton.setEnabled(false);
            }

            promotedActionsLibrary.addItemClear(ContextCompat.getDrawable(getApplicationContext(),
                                                                          R.drawable.selector_ic_menu_clear), mOnPanelClickListener, "menu_clear");
            promotedActionsLibrary.addItemFile(ContextCompat.getDrawable(getApplicationContext(),
                                                                         R.drawable.selector_ic_menu_file), mOnPanelClickListener, "menu_file");

            if (mRoomType == 1) {
                promotedActionsLibrary.addItemLock(ContextCompat.getDrawable(getApplicationContext(),
                                                                             R.drawable.ic_menu_unlock), mOnPanelClickListener, "menu_lock");

                promotedActionsLibrary.menuLockButton.setEnabled(false);
                promotedActionsLibrary.menuLockButton.setSelected(true);
            }else{
                promotedActionsLibrary.addItemLimitAll(
                        ContextCompat.getDrawable(getApplicationContext(),
                                                  R.drawable.ic_menu_allowtalk), mOnPanelClickListener, "menu_limitall");

                promotedActionsLibrary.menuLimitAllButton.setEnabled(false);
            }

            promotedActionsLibrary.menuFileButton.setEnabled(false);
            promotedActionsLibrary.menuClearButton.setEnabled(false);
        }

        if (mUserType != 3) {
            if (mUserType == 2) {
                promotedActionsLibrary.addItemFile(ContextCompat.getDrawable(getApplicationContext(),
                                                                             R.drawable.selector_ic_menu_file), mOnPanelClickListener, "menu_file");
                promotedActionsLibrary.menuFileButton.setEnabled(false);
            }

            promotedActionsLibrary.addItemEdit(ContextCompat.getDrawable(getApplicationContext(),
                                                                         R.drawable.ic_menu_edit_uncheck),
                                               mOnPanelClickListener,
                                               "menu_edit");
            promotedActionsLibrary.addItem(ContextCompat.getDrawable(getApplicationContext(),
                                                                     R.drawable.selector_ic_menu_camera),
                                           mOnPanelClickListener,
                                           "menu_camera");
            promotedActionsLibrary.meunEditButton.setEnabled(false);
            promotedActionsLibrary.menuCameraButton.setEnabled(false);
        } else {
            if (mRoomType != 1) {
                promotedActionsLibrary.addItemLimitAll(
                        ContextCompat.getDrawable(getApplicationContext(),
                                                  R.drawable.ic_menu_allowtalk),
                        mOnPanelClickListener, "menu_limitall");
                promotedActionsLibrary.addItemFile(ContextCompat.getDrawable(getApplicationContext(),
                                                                             R.drawable.selector_ic_menu_file),
                                                   mOnPanelClickListener, "menu_file");
                promotedActionsLibrary.menuLimitAllButton.setEnabled(false);
                promotedActionsLibrary.menuFileButton.setEnabled(false);
            }
        }
        promotedActionsLibrary.addMainItem(ContextCompat.getDrawable(getApplicationContext(),
                                                                     R.drawable.ic_add_check));
        promotedActionsLibrary.mainImageButton.setEnabled(false);

        promotedActionsLibrary.mainImageButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (promotedActionsLibrary.isMenuOpened) {
                    promotedActionsLibrary.closePromotedActions().start();
                    promotedActionsLibrary.isMenuOpened = false;

                    if (mUserType != 3 && promotedActionsLibrary.meunEditButton.isSelected()) {
                        promotedActionsLibrary.meunEditButton.setSelected(false);
                        promotedActionsLibrary.meunEditButton.setImageDrawable(ContextCompat.getDrawable(
                                getApplicationContext(), R.drawable.ic_menu_edit_uncheck));

                        mIsMovingPic = true;
                    }
                } else {
                    promotedActionsLibrary.isMenuOpened = true;
                    promotedActionsLibrary.openPromotedActions().start();
                }

                if ((mUserType == 2 && mAnchor) || mUserID == mHostID || mUserType == 3) {
                    promotedActionsLibrary.menuFileButton.setVisibility(View.VISIBLE);
                } else {
                    promotedActionsLibrary.menuFileButton.setVisibility(View.GONE);
                }
            }
        });
    }

    /**
     * 显示文件目录的对话框
     */
    private void showFileDialog() {
        ListView listView = new ListView(this);
        listView.setAdapter(new CatalogListAdapter(this, mCatalogLists));

        AlertDialog.Builder builder = new AlertDialog.Builder(this).setView(listView);
        final AlertDialog   dialog  = builder.show();
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);

        if (mCatalogLists != null) {
            for (CatalogBean catalogbean : mCatalogLists) {
                if (mFileID == catalogbean.getFileId()) {
                    catalogbean.setCurrentpage(currentPage);
                    catalogbean.setCurrentaction(mCurrentaction);
                    if (mPageNums != 1) {
                        catalogbean.setPageNums(mPageNums + "");
                    }
                }
            }
        }

        try {
            listView.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    if (mGraffitiView != null) {

                        GraffitiPathPage graffitiPathPage = mGraffitiView.getGraffitiPathPage();
                        String fileid = graffitiPathPage.getFileid();
                        int current = graffitiPathPage.getCurrentPage();

                        String fileIdKey = fileid + "-" + current;

                        for (int j = 0; j < mGraffitiPaintData.size() ; j++) {
                            if (mGraffitiPaintData.get(j).getFileId().equals(fileIdKey))
                            {
                                mGraffitiPaintData.remove(j);
                            }
                        }

                        if (mGraffitiPathPageMap.containsKey(fileIdKey)) {
                            mGraffitiPathPageMap.remove(fileIdKey);
                        }

                        if (mGraffitiView.mPathStackBackup.size() > 0) {
                            int size = mGraffitiView.mGraffitiOrderData.size() - mGraffitiView.mPathStackBackup.size();

                            for (int i = 0; i < size; i++) {
                                mGraffitiView.mGraffitiOrderData.remove(mGraffitiView.mGraffitiOrderData.size() - 1);
                            }
                            String paintmsg = new Gson().toJson(mGraffitiView.mGraffitiOrderData);

                            if (mSyncPage || mRoomType == 1 || mAnchor || mUserID == mHostID) {
                                mGraffitiPaintData.add(new GraffitiPaintmsgBean(fileIdKey, paintmsg));
                                mGraffitiPathPageMap.put(fileIdKey, graffitiPathPage);
                            }
                        }

                        mGraffitiView.clear();
                        mFrameLayout.removeAllViews();
                        mGraffitiView = null;
                    }

                    mTurnPage = true;

                    CatalogBean catalogBean = mCatalogLists.get(position);

                    if (IsPlaying) {
                        IsPlaying = false;

                        String mp3Name = SharedPreferencesUtils.getParam(VideoActivity.this, mFileID + "", "").toString();
                        String mp3Path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/download/" + mp3Name + ".mp3";

                        musicPause(mp3Path);
                        mIvMusicPlayOrPause.setImageResource(R.drawable.selector_music_play);
                        SendMusicCommandMessage.sendMessge(0, mFileID, "pause", mGroup);
                    }

                    String fileName = catalogBean.getFileName();

                    if (fileName.contains(".mp3") || fileName.contains(".wav") || fileName.contains(".wma"))
                    {
                        startWebMode(false);

                        mRlMusic.setVisibility(View.VISIBLE);
                        mLlMusicControl.setVisibility(View.VISIBLE);
                        mMusicFileName = catalogBean.getFileName();
                        mTvMusicName.setText(mMusicFileName);
                        mFrameLayout.setVisibility(View.GONE);
                        mArrowRight.setVisibility(View.GONE);
                        mArrowLeft.setVisibility(View.GONE);
                    }else {
                        startWebMode(false);

                        mRlMusic.setVisibility(View.GONE);
                        mFrameLayout.setVisibility(View.VISIBLE);

                        if (catalogBean.getCurrentpage() == 1) {
                            mArrowRight.setVisibility(View.VISIBLE);
                        } else if (catalogBean.getCurrentpage() == Integer.parseInt(catalogBean.getPageNums()))
                        {
                            mArrowLeft.setVisibility(View.VISIBLE);
                        } else {
                            mArrowRight.setVisibility(View.VISIBLE);
                            mArrowLeft.setVisibility(View.VISIBLE);
                        }
                    }

                    if (catalogBean.getFileType().equals("H5")) {
                        startWebMode(true);
                    }

                    fileDir = catalogBean.getFileDir();
                    currentPage = catalogBean.getCurrentpage();
                    mFileID = catalogBean.getFileId();
                    if (catalogBean.getPageNums() == null || catalogBean.getPageNums().equals("")) {
                        mPageNums = 0;
                    } else {
                        mPageNums = Integer.parseInt(catalogBean.getPageNums());
                    }

                    mWhiteBoardBean.setFileid(mFileID);
                    if (mGraffitiView != null) {
                        mGraffitiView.setWhiteBoardBeanInfo(mWhiteBoardBean);
                    }

                    String pageTextString = getResources().getString(R.string.pageTextString);
                    String pageText = String.format(pageTextString,currentPage,mPageNums);
                    mPageText.setText(pageText);

                    if (isWebMode) {
                        switchAndShareWeb(mFileID, fileDir, fileName);
                    } else {
                        String url = Constant.getDocUrl() + fileDir + "/" + currentPage + ".jpg";
                        LogUtil.e("imgurl", url);

                        loadImageBitmap(url);

                        upLoadCurrentTextBook(fileDir, currentPage);
                    }

                    String mp3Name = SharedPreferencesUtils.getParam(VideoActivity.this, mFileID + "", "").toString();
                    String mp3Path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/download/" + mp3Name + ".mp3";
                    if (map.containsKey(mp3Path)) {
                        MediaPlayer mediaPlayer = map.get(mp3Path);
                        mSpbMusic.setProgress(mediaPlayer.getCurrentPosition());
                        mSpbMusic.setMax(mediaPlayer.getDuration());
                        mTvMusicCurrentTime.setText(timeFormat.format(mediaPlayer.getCurrentPosition()));
                        mTvMusicDuration.setText(timeFormat.format(mediaPlayer.getDuration()));
                    } else {
                        mSpbMusic.setProgress(0);
                        mTvMusicCurrentTime.setText("00:00");
                        mTvMusicDuration.setText("00:00");
                    }

                    dialog.dismiss();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void unLockUser(boolean unlock, int userID) {
        SendLockMessage.sendMessge(unlock, userID, mGroup);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mFilePath != null) {
            outState.putString("cameraFilePath", mFilePath);
            LogUtil.d("onSaveInstanceState");
            LogUtil.d(mFilePath);
        }
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (TextUtils.isEmpty(mFilePath)) {
            mFilePath = savedInstanceState.getString("cameraFilePath");
            LogUtil.d("onRestoreInstanceState");
            LogUtil.d(mFilePath);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==REQUEST_CODE_SETTING) {
            Intent intent = new Intent(VideoActivity.this, LoginActivity.class);
            startActivity(intent);
            VideoActivity.this.finish();
        }

        if (requestCode == 1) {
            rtcEngine.joinChannel(channelkey, mRoomID + "", "", mUserID);

            if (resultCode == RESULT_OK) {
                Bitmap bitmap = BitmapFactory.decodeFile(mFilePath);
                compressPhoto(bitmap);
            }
        } else if (requestCode == 2) {
            if (data != null) {
                Uri mImageCaptureUri = data.getData();
                if (mImageCaptureUri != null) {/**选取图片*/
                    Bitmap image;
                    try {
                        String filedir = SharedPreferencesUtils.getParam(VideoActivity.this,
                                                                         mWhiteBoardBean.getFileid() + "",
                                                                         "null").toString();
                        String imgUrl = Constant.getDocUrl() + filedir + "/" + mWhiteBoardBean.getCurrentpage() + ".jpg";
                        loadImageBitmap(imgUrl);

                        //这个方法是根据Uri获取Bitmap图片的静态方法
                        image = MediaStore.Images.Media.getBitmap(this.getContentResolver(),
                                                                  mImageCaptureUri);
                        compressPhoto(image);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        if (resultCode == RESULT_CANCELED ) {
            if (requestCode == 1) {
                rtcEngine.joinChannel(channelkey, mRoomID + "", "", mUserID);
            }

            String filedir = SharedPreferencesUtils.getParam(VideoActivity.this, mWhiteBoardBean.getFileid() + "", "null").toString();
            String imgUrl = Constant.getDocUrl() + filedir + "/" + mWhiteBoardBean.getCurrentpage() + ".jpg";
            loadImageBitmap(imgUrl);
        }
    }

    /**
     * 压缩图片
     * @param image
     */
    private void compressPhoto(Bitmap image) {
        if (image != null) {
            FileUtils.verifyStoragePermissions(VideoActivity.this);//权限
            final String temporaryName = FileUtils.creatFileName();//临时文件名
            new CompressPhotoUtils().CompressPhoto(VideoActivity.this, image, temporaryName, new CompressPhotoUtils.CompressCallBack() {
                @Override
                public void success(ByteArrayInputStream byteArrayInputStream) {
                    if (byteArrayInputStream != null) {
                        temporaryPath = FileUtils.saveBitmapToCamera(byteArrayInputStream, temporaryName, mContext);//保存临时图片

                        if (TextUtils.isEmpty(temporaryPath) || TextUtils.isEmpty(temporaryName)) {
                            Toast.makeText(mContext, "图片上传失败，请重试！", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        //上传文件
                        upLoadService = new upLoadPhotoService(upLoadHanler);
                        upLoadService.upLoad(temporaryPath, temporaryName, mUserID + "");
                    }
                }
            });
        }
    }

    //上传图片
    private upLoadPhotoService upLoadService;
    //图片文件保存路径
    private String             temporaryPath;

    /**
     * 截屏功能
     */
    private void penScreenShot() {
        String fileName = FileUtils.creatFileName();
        temporaryPath = FileUtils.DCIMCamera_PATH + fileName;
        boolean success = ScreenShot.shoot(this, new File(temporaryPath), this);
        if (success) {
            Toast.makeText(this, "截屏成功", Toast.LENGTH_SHORT).show();

            if (TextUtils.isEmpty(temporaryPath) || TextUtils.isEmpty(fileName)) {
                Toast.makeText(mContext, "图片上传失败，请重试！", Toast.LENGTH_SHORT).show();
                return;
            }

            upLoadService = new upLoadPhotoService(upLoadHanler);
            upLoadService.upLoad(temporaryPath, fileName, mUserID + "");
        }
    }

    /**
     * 进度条弹框
     */
    private UpPhotoProgressDialog mUpPhotoProgressDialog;

    private void photoProgressDialog(Bitmap imageBitmap) {
        mUpPhotoProgressDialog = new UpPhotoProgressDialog(this, imageBitmap, new UpPhotoProgressDialog.CancelCallBack() {
            @Override
            public void cancelOnClick() {//取消上传
                //取消请求
                upLoadService.getHttpHandler().cancel();
                mUpPhotoProgressDialog.dismiss();
            }
        });
        Window dialogWindow = mUpPhotoProgressDialog.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 20;//设置Dialog距离底部的距离
        dialogWindow.setAttributes(lp);
        mUpPhotoProgressDialog.setCanceledOnTouchOutside(false);
        mUpPhotoProgressDialog.show();
    }

    /**
     * 选择图片dialog
     */
    private Dialog dialog;

    public void showDailogcamera() {
        if (dialog != null && dialog.isShowing()) {
            return;
        }
        dialog = new Dialog(this, R.style.ActionSheetDialogStyle);
        View inflate = LayoutInflater.from(this).inflate(R.layout.dialog_layout, null);
        Button choosePhoto = (Button) inflate.findViewById(R.id.choosePhoto);
        Button takePhoto = (Button) inflate.findViewById(R.id.takePhoto);
        Button screenshots = (Button) inflate.findViewById(R.id.screenshots);
        Button cancel = (Button) inflate.findViewById(R.id.btn_cancel);
        choosePhoto.setOnClickListener(dialogListener);
        takePhoto.setOnClickListener(dialogListener);
        screenshots.setOnClickListener(dialogListener);
        cancel.setOnClickListener(dialogListener);

        dialog.setContentView(inflate);
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 20;//设置Dialog距离底部的距离
        dialogWindow.setAttributes(lp);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    private OnClickListener dialogListener = new OnClickListener() {

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.takePhoto:
                    try {
                        //拍照我们用Action为MediaStore.ACTION_IMAGE_CAPTURE，
                        //有些人使用其他的Action但我发现在有些机子中会出问题，所以优先选择这个
                        rtcEngine.leaveChannel();
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        //intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                        intent.addCategory(Intent.CATEGORY_DEFAULT);

                        String pictureFileName="/IMG_" + new SimpleDateFormat("yyyyMMdd_hhmmss").format(System.currentTimeMillis())+".jpg";

                        LogUtil.e("filedir", pictureFileName);

                        String fileDir = Environment.getExternalStorageDirectory() + "/DCIM/Camera";
                        //指定一个图片路径对应的file对象
                        File file=new File(fileDir);
                        if(!file.exists())
                        {
                            file.mkdirs();//创建文件夹
                        }
                        mFilePath = fileDir + pictureFileName;

                        LogUtil.e("filedir", mFilePath);

                        int currentAPIVersion = Build.VERSION.SDK_INT;
                        Uri imageUri;
                        if (currentAPIVersion < 24) {
                            imageUri = Uri.fromFile(new File(mFilePath));
                        }else {
                            ContentValues contentValues = new ContentValues(1);
                            contentValues.put(MediaStore.Images.Media.DATA, mFilePath);
                            imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                        }
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                        startActivityForResult(intent, 1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    dialog.dismiss();
                    break;
                case R.id.choosePhoto:
                    try {
                        //选择照片的时候也一样，我们用Action为Intent.ACTION_GET_CONTENT，
                        //有些人使用其他的Action但我发现在有些机子中会出问题，所以优先选择这个
                        Intent intent = new Intent();
                        intent.setType("image/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(intent, 2);
                    } catch (ActivityNotFoundException e) {
                    }
                    dialog.dismiss();
                    break;
                case R.id.screenshots:
                    dialog.dismiss();
                    penScreenShot();
                    break;
                case R.id.btn_cancel:
                    dialog.dismiss();
                    break;
            }
        }
    };

    private int     numbar       = 0;
    private Handler upLoadHanler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0://上传开始，显示进度条
                    Bitmap image = BitmapFactory.decodeFile(temporaryPath);
                    photoProgressDialog(image);
                    break;

                case 1://更新进度条
                    numbar = msg.arg1;
                    LogUtil.e("上传", "上传进度：" + numbar);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mUpPhotoProgressDialog.squareProgressBar.setProgress(numbar);
                        }
                    });
                    break;

                case 2://取消上传成功
                    Toast.makeText(VideoActivity.this, "上传已取消", Toast.LENGTH_SHORT).show();
                    FileUtils.deleteFile(temporaryPath);//删除临时文件
                    break;

                case 3://上传成功
                    if (isWebMode) {
                        startWebMode(false);
                    }

                    if (mGraffitiView != null) {
                        mGraffitiView = null;
                        mFrameLayout.removeAllViews();
                    }

                    if (mCatalogLists != null) {
                        for (CatalogBean catalogbean : mCatalogLists) {
                            if (mFileID == catalogbean.getFileId()) {
                                catalogbean.setCurrentpage(currentPage);
                                catalogbean.setPageNums(mPageNums + "");
                            }
                        }
                    } else {
                        mCatalogLists = new ArrayList<>();
                    }

                    String resultStr = (String) msg.obj;
                    try {
                        boolean Result = false;
                        String FileID = "";
                        String FileName = "";
                        String FileDir = "";

                        JSONObject object = new JSONObject(resultStr);
                        if (object.has("Result")) {
                            Result = object.getBoolean("Result");
                        }
                        if (object.has("FileID")) {
                            FileID = object.getString("FileID");
                        }
                        if (object.has("FileName")) {
                            FileName = object.getString("FileName");
                        }
                        if (object.has("FileDir")) {
                            FileDir = object.getString("FileDir");
                        }

                        if (!TextUtils.isEmpty(FileID) && !TextUtils.isEmpty(FileDir) && !TextUtils.isEmpty(FileName)) {

                            SharedPreferencesUtils.setParam(VideoActivity.this, FileID, FileDir);
                            SharedPreferencesUtils.setParam(VideoActivity.this, FileID + "pagenum", 1);

                            //发送打开共享的文件命令
                            //SendOpenFileMessge.sendMessge(Integer.parseInt(FileID), FileName, FileDir, 1, egine, mGroup);
                            //发送跳转翻页命令
                            //SendPageturnMessge.sendMessge(Integer.parseInt(FileID), egine, mGroup);

                            mWhiteBoardBean.setCurrentpage(1);
                            mWhiteBoardBean.setPagenum(1);
                            mWhiteBoardBean.setFiledir(FileDir);
                            mWhiteBoardBean.setFileid(Integer.parseInt(FileID));
                            mWhiteBoardBean.setFilename(FileName);
                            currentPage = 1;
                            mPageNums = 1;
                            fileDir = FileDir;
                            mFileID = Integer.parseInt(FileID);

                            CatalogBean catalogBean = new CatalogBean(FileName, FileDir, "1", 1,
                                                            Integer.parseInt(FileID));
                            catalogBean.setFileType("JPG");
                            mCatalogLists.add(catalogBean);

                            final String url = Constant.getDocUrl() + FileDir + "/" + currentPage +".jpg";
                            final String fileName = FileName;
                            upLoadHanler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    SendOpenFileMessge.sendMessge(mFileID, fileName, fileDir, 1, egine, mGroup);
                                    loadImageBitmap(url);
                                }
                            }, 200);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    mUpPhotoProgressDialog.textView.setText("上传成功");
                    delayCloaseDialog();
                    FileUtils.deleteFile(temporaryPath);//删除临时文件
                    break;

                case 4://失败
                    String msgStr = (String) msg.obj;
                    Toast.makeText(VideoActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                    FileUtils.deleteFile(temporaryPath);//删除临时文件
                    break;

                case CREATE_DRAW_VIEW://教材图片获取成功

                    if (mGraffitiView != null && mGraffitiPathPageMap != null) {
                        GraffitiPathPage graffitiPathPage = mGraffitiView.getGraffitiPathPage();
                        String fileid = graffitiPathPage.getFileid();
                        int current = graffitiPathPage.getCurrentPage();
                        String fileIdKey = fileid + "-" + current;

                        for (int j = 0; j < mGraffitiPaintData.size() ; j++) {
                            if (mGraffitiPaintData.get(j).getFileId().equals(fileIdKey))
                            {
                                mGraffitiPaintData.remove(j);
                            }
                        }

                        if(mGraffitiPathPageMap.containsKey(fileIdKey)){
                            mGraffitiPathPageMap.remove(fileIdKey);
                        }

                        if (mGraffitiView.mPathStackBackup.size() > 0) {
                            int size = mGraffitiView.mGraffitiOrderData.size() - mGraffitiView.mPathStackBackup.size();

                            for (int i = 0; i < size; i++) {
                                mGraffitiView.mGraffitiOrderData.remove(mGraffitiView.mGraffitiOrderData.size() - 1);
                            }

                            String paintmsg = new Gson().toJson(mGraffitiView.mGraffitiOrderData);

                            if (mSyncPage || mRoomType == 1 || mAnchor || mUserID == mHostID) {
                                mGraffitiPathPageMap.put(fileIdKey, graffitiPathPage);
                                mGraffitiPaintData.add(new GraffitiPaintmsgBean(fileIdKey, paintmsg));
                            }
                        }

                        mGraffitiView = null;
                        mFrameLayout.removeAllViews();
                    }

                    if ( mTurnPage && null != mWhiteBoardBean ) {
                        mWhiteBoardBean.setCurrentpage(currentPage);
                    }

                    String pageTextString = getResources().getString(R.string.pageTextString);
                    String pageText = String.format(pageTextString,currentPage,mPageNums);
                    mArrowRight.setVisibility(currentPage == mPageNums ? View.GONE : View.VISIBLE);
                    mPageText.setText(pageText);

                    createDrawView();

                    break;
            }
        }
    };

    //延迟关闭diolog
    private void delayCloaseDialog() {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mUpPhotoProgressDialog.dismiss();
            }
        }, 1500);//1.5秒后执行Runnable中的run方法
    }

    public static final int RESULT_ERROR     = -111; // 出现错误
    public static final int CREATE_DRAW_VIEW = -5;
    public static final int GET_PHOTO_ERROR  = -4;

    //画板的底图
    private Bitmap mGraffitiBitmap;

    private FrameLayout  mFrameLayout;
    private GraffitiView mGraffitiView;

    private Runnable mUpdateScale;

    private int mTouchMode;
    private boolean mIsMovingPic = true;

    // 手势操作相关
    private float mOldScale, mOldDist, mNewDist, mToucheCentreXOnGraffiti,
            mToucheCentreYOnGraffiti, mTouchCentreX, mTouchCentreY;// 双指距离

    private float mTouchLastX, mTouchLastY;

    private       boolean mIsScaling = false;
    private       float   mScale     = 1;
    private final float   mMaxScale  = 3.5f; // 最大缩放倍数
    private final float   mMinScale  = 0.25f; // 最小缩放倍数
    // 放大\缩小，  全屏（隐藏画板工具面板按钮）， 画板工具
    private View mBtnHidePanel;

    private int mTouchSlop;

    private GraffitiParams mGraffitiParams;

    private void createDrawView() {

        if (mGraffitiParams == null) {
            return;
        }
        if (mGraffitiBitmap == null) {
            return;
        }

        mGraffitiView = new GraffitiView(this, mGraffitiBitmap, mGraffitiParams.mEraserImageIsResizeable,
                new GraffitiView.GraffitiListener() {

                    @Override
                    public void onError(int i, String msg) {
                        setResult(RESULT_ERROR);
                        finish();
                    }

                    @Override
                    public void onReady() { //准备工作完成
                        mGraffitiView.setWhiteBoardBeanInfo(mWhiteBoardBean);

                        if (mTurnPage) {// 是否手动翻页
                            mTurnPage = false;
                            if (mWhiteBoardBean != null && !TextUtils.isEmpty(mWhiteBoardBean.getFileid() + "") &&
                                    mGraffitiPathPageMap != null && mGraffitiPathPageMap.size() != 0) {
                                String fileid = mWhiteBoardBean.getFileid() + "";
                                if (mGraffitiPathPageMap.containsKey(fileid + "-" + String.valueOf(currentPage))) {
                                    GraffitiPathPage graffitiPathPage = mGraffitiPathPageMap.get(fileid + "-" + String.valueOf(currentPage));

                                    String paintMsg = "";
                                    for (GraffitiPaintmsgBean graffitiPaintmsgBean : mGraffitiPaintData) {
                                        if (graffitiPaintmsgBean.getFileId().equals(fileid + "-" + String.valueOf(currentPage)))
                                        {
                                            paintMsg = graffitiPaintmsgBean.getPaintMsg();
                                        }
                                    }

                                    mGraffitiView.restoreDrawPath(graffitiPathPage.getmPathMap(), paintMsg);
                                }
                            }
                        } else {
                            if (mWhiteBoardBean != null && !TextUtils.isEmpty(mWhiteBoardBean.getFileid() + "") && mGraffitiPathPageMap != null && mGraffitiPathPageMap.size() != 0) {
                                String fileid = mWhiteBoardBean.getFileid() + "";
                                int page = mWhiteBoardBean.getCurrentpage();
                                if (mGraffitiPathPageMap.containsKey(fileid + "-" + String.valueOf(page))) {
                                    GraffitiPathPage graffitiPathPage = mGraffitiPathPageMap.get(fileid + "-" + String.valueOf(page));

                                    String paintMsg = "";
                                    for (GraffitiPaintmsgBean graffitiPaintmsgBean : mGraffitiPaintData) {
                                        if (graffitiPaintmsgBean.getFileId().equals(fileid + "-" + String.valueOf(currentPage)))
                                        {
                                            paintMsg = graffitiPaintmsgBean.getPaintMsg();
                                        }
                                    }

                                    mGraffitiView.restoreDrawPath(graffitiPathPage.getmPathMap(), paintMsg);
                                }
                            }
                        }

                        if ( differentPage ) {
                            differentPage = false;
                            currentPage = mWhiteBoardBean.getCurrentpage();
                            mGraffitiView.storeGraffitiLineData(mWhiteBoardBean);
                            doPaintGraffiti(mWhiteBoardBean);
                        }

                        if (differentPageText) {
                            differentPageText = false;
                            mGraffitiView.storeGraffitiTextData(textWhiteBoardBean.getMessage());
                            doPaintTextGraffiti(textWhiteBoardBean);
                        }
                    }
                });
        mGraffitiView.setPaintSize(mGraffitiParams.mPaintSize);
        mGraffitiView.setIsDrawableOutside(mGraffitiParams.mIsDrawableOutside);
        mFrameLayout.addView(mGraffitiView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        mTouchSlop = ViewConfiguration.get(getApplicationContext()).getScaledTouchSlop();

        mGraffitiView.mTeacherCurrentPage = mTeacherCurrentPage;
        mGraffitiView.mRoomType = mRoomType;
        mGraffitiView.mAnchor = mAnchor;

        //画板布局
        initDrawView();
    }


    private void initDrawView() {

        // 添加涂鸦的触摸监听器，移动图片位置
        mGraffitiView.setOnTouchListener(new View.OnTouchListener() {

            boolean mIsBusy = false; // 避免双指滑动，手指抬起时处理单指事件。

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                //if (null!=mGraffitiView&&null!=promotedActionsLibrary&&null != promotedActionsLibrary.mainImageButton && null != promotedActionsLibrary.meunEditButton) {
                if (null!=mGraffitiView&&null!=promotedActionsLibrary&&null != promotedActionsLibrary.mainImageButton) {
                    // 隐藏设置面板
                    if (!mIsMovingPic) {
                        boolean isMove = false;
                        switch (event.getAction() & MotionEvent.ACTION_MASK) {
                            case MotionEvent.ACTION_DOWN:
                                mTouchMode = 1;
                                mTouchLastX = event.getX();
                                mTouchLastY = event.getY();
                            case MotionEvent.ACTION_UP:
                                if (mTouchMode < 2 && Math.abs((int) mTouchLastY) < 30 && !isMove) {
                                    setAnimatorSet();
                                }
                            case MotionEvent.ACTION_CANCEL:
                                mTouchMode = 0;
                            case MotionEvent.ACTION_MOVE:
                                isMove = true;
                            case MotionEvent.ACTION_POINTER_UP:
                                mTouchMode -= 1;
                            case MotionEvent.ACTION_POINTER_DOWN:
                                mTouchMode += 1;
                        }
                        return false;  // 交给下一层的涂鸦处理
                    }
                    mScale = mGraffitiView.getScale();
                    switch (event.getAction() & MotionEvent.ACTION_MASK) {
                        case MotionEvent.ACTION_DOWN:
                            isActionMove = false;
                            mTouchMode = 1;
                            mTouchLastX = event.getX();
                            mTouchLastY = event.getY();
                            return true;
                        case MotionEvent.ACTION_UP:
                            if (!isActionMove) {
                                setAnimatorSet();
                            }
                        case MotionEvent.ACTION_CANCEL:
                            mTouchMode = 0;
                            return true;
                        case MotionEvent.ACTION_MOVE:
                            if (mTouchMode < 2) { // 单点滑动
                                if (mIsBusy) { // 从多点触摸变为单点触摸，忽略该次事件，避免从双指缩放变为单指移动时图片瞬间移动
                                    mIsBusy = false;
                                    mTouchLastX = event.getX();
                                    mTouchLastY = event.getY();
                                    return true;
                                }
                                float tranX = event.getX() - mTouchLastX;
                                float tranY = event.getY() - mTouchLastY;
                                mGraffitiView.setTrans(mGraffitiView.getTransX() + tranX, mGraffitiView.getTransY() + tranY);
                                mTouchLastX = event.getX();
                                mTouchLastY = event.getY();
                                if (Math.abs((int) tranX) > 16 || Math.abs((int) tranY) > 16) {
                                    isActionMove = true;
                                }
                            } else { // 多点
                                mNewDist = spacing(event);// 两点滑动时的距离
                                if (Math.abs(mNewDist - mOldDist) >= mTouchSlop) {
                                    float scale = mNewDist / mOldDist;
                                    mScale = mOldScale * scale;

                                    if (mScale > mMaxScale) {
                                        mScale = mMaxScale;
                                    }
                                    if (mScale < mMinScale) { // 最小倍数
                                        mScale = mMinScale;
                                    }
                                    // 围绕坐标(0,0)缩放图片
                                    mGraffitiView.setScale(mScale);
                                    // 缩放后，偏移图片，以产生围绕某个点缩放的效果
                                    float transX = mGraffitiView.toTransX(mTouchCentreX, mToucheCentreXOnGraffiti);
                                    float transY = mGraffitiView.toTransY(mTouchCentreY, mToucheCentreYOnGraffiti);
                                    mGraffitiView.setTrans(transX, transY);
                                }
                                if (Math.abs(mNewDist) > 16) {
                                    isActionMove = true;
                                }
                            }
                            return true;
                        case MotionEvent.ACTION_POINTER_UP:
                            mTouchMode -= 1;
                            return true;
                        case MotionEvent.ACTION_POINTER_DOWN:
                            mTouchMode += 1;
                            mOldScale = mGraffitiView.getScale();
                            mOldDist = spacing(event);// 两点按下时的距离
                            mTouchCentreX = (event.getX(0) + event.getX(1)) / 2;// 不用减trans
                            mTouchCentreY = (event.getY(0) + event.getY(1)) / 2;
                            mToucheCentreXOnGraffiti = mGraffitiView.toX(mTouchCentreX);
                            mToucheCentreYOnGraffiti = mGraffitiView.toY(mTouchCentreY);
                            mIsBusy = true; // 标志位多点触摸
                            return true;
                    }
                }
                return true;
            }
        });
    }

    /**
     * 计算两指间的距离
     *
     * @param event
     * @return
     */
    private float spacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return (float) Math.sqrt(x * x + y * y);
    }

    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {

        try {
            if (isVoucherJump) {
                uploadAgoraLog();
            }

            if (mWebView != null) {
                mWebView.destroy();
            }

            if (mVideoStreamShow) {
            }

            if (rtcEngine != null) {
                rtcEngine.leaveChannel();
                rtcEngine.destroy();
                rtcEngine = null;

            }if(egine!=null){
                ThreadUtils.runOnSubThread(new Runnable() {
                    @Override
                    public void run() {
                        egine.LeaveGroup(mGroup);
                        egine.UnRegister();
                        egine = null;
                    }
                });
            }

            if (mVolumeReceiver != null) {
                unregisterReceiver(mVolumeReceiver);
                mVolumeReceiver = null;
            }

            if (mWifiChangeBroadcastReceiver != null) {
                unregisterReceiver(mWifiChangeBroadcastReceiver);
                mWifiChangeBroadcastReceiver = null;
            }

            super.onDestroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**计时器动画*/
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    private void setAnimatorSet() {
        AnimatorSet animation = new AnimatorSet();
        ObjectAnimator objectAnimator;
        if (isTimerShow){
            objectAnimator  = ObjectAnimator.ofFloat(mTimerView,
                    View.TRANSLATION_Y, 0f, -mTimerLayoutHeight );
        } else {
            objectAnimator  = ObjectAnimator.ofFloat(mTimerView,
                    View.TRANSLATION_Y, -mTimerLayoutHeight, 0f);
        }
        objectAnimator.setRepeatCount(0);
        objectAnimator.setDuration(600);
        animation.playTogether(objectAnimator);
        animation.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
                isAnimatorPlay = true;
            }
            @Override
            public void onAnimationEnd(Animator animator) {
                if (isTimerShow){
                    isTimerShow = false;
                } else {
                    isTimerShow = true;
                }
                isAnimatorPlay = false;

                if (isTimerShow) {
                    timerHandler.postDelayed(runnable, 5000);// 打开定时器，执行操作
                } else {
                    timerHandler.removeCallbacks(runnable);
                }

            }
            @Override
            public void onAnimationCancel(Animator animator) {}
            @Override
            public void onAnimationRepeat(Animator animation) {}
        });

        if ( ! isAnimatorPlay) {
            animation.start();
        }

        if ( ! isTimerShow) {
            timerHandler.removeCallbacks(runnable);
        }

    }

    // 定时器任务
    final Handler timerHandler = new Handler();
    Runnable runnable = new Runnable(){
        @Override
        public void run() {
            setAnimatorSet();
            timerHandler.removeCallbacks(this);
        }
    };

    /**获取计时器控件高度*/
    private void getTimerViewHeight() {
        mTimerView.post(new Runnable() {
            @Override
            public void run() {
                mTimerLayoutHeight = mTimerView.getHeight(); // 获取高度
            }
        });
    }
}
